点击事件中使用jQuery获取输入框的值
点击事件中使用jQuery获取输入框的值
这个问题在这里已经有了答案:
我有以下内容:
$('.checkbox').click(function () { console.log(this); $.ajax({ type:'POST', url: '/loadProducts', data: {}, success: function(response) { console.log(response); $('.js-products').html(response); }}); return false; });
现在当我进行console.log(this)
时,它返回:
我该如何获取输入名称(性别)?以及复选框是否被选中?
admin 更改状态以发布 2023年5月21日
您可以使用 jQuery
的方法 find
获取输入对象,然后使用 jQuery
的 prop
方法来检查是否选择了女性。
$('.checkbox').click(function () { // to get the input var $input = $(this).find('input'); // to check if the checkbox is checked or not console.info($input.prop('checked')); $.ajax({ type:'POST', url: '/loadProducts', data: {}, success: function(response) { console.log(response); $('.js-products').html(response); }}); return false; });
这里的回答(链接)告诉你如何通过名称检索元素。然而,这里的难点在于您的名称本身包含括号。因此,为了解决这个问题,您需要在名称周围添加引号 ",如下面的示例所示。
一旦您获得了元素,您可以简单地使用 .prop('checked')
来检索当前值。
$('.checkbox').click(function () { console.log(this); var theValue = $('input[name="gender[women]"]').prop('checked'); //<--HERE IS HOW YOU GET THE VALUE console.log(theValue); $.ajax({ type:'POST', url: '/loadProducts', data: {}, success: function(response) { console.log(response); $('.js-products').html(response); }}); return false; });