点击使用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)
,它返回:
如何获取输入名称(性别)? 以及复选框是否已签出?
这里的答案向您展示了如何按名称检索元素。 但是,这里棘手的部分是你的名字本身有括号。 因此,要解决此问题,您需要在名称周围添加引号,如下面的示例所示。
获得元素后,您可以简单地执行.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; });
你可以使用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; });
使用$(this).find(":checkbox")
来获取复选框。 然后你可以使用.attr('name')
来获取名称,并使用.is(":checked")
来获取它是否被检查。
您不应该return false
因为这会阻止单击复选框以实际更改框的状态。
$('.checkbox').click(function() { console.log(this); var checkbox = $(this).find(":checkbox"); var name = checkbox.attr("name"); var checked = checkbox.is(":checked"); console.log(name + "is " + (checked ? "" : "not ") + "checked"); $.ajax({ type: 'POST', url: '/loadProducts', data: {}, success: function(response) { console.log(response); $('.js-products').html(response); } }); });
如果我正确地解释了这个问题,你可以将一个HTML字符串response
传递给jQuery()
,从HTML字符串创建一个jQuery对象,然后调用.attr("name")
和.prop("checked")
:
var input = $(response).find("input"); console.log(input.attr("name"), input.prop("checked"));
如何获取输入名称(性别)? 是否签出了复选框?
如果您尝试获取clicked元素的.name
和.checked
属性值,可以调用.querySelector()
链接到: .checkbox
元素,使用选择器"input[type=checkbox]"
; .getAttribute()
其中"name"
作为参数, .replace()
使用RegExp
/^\w+\[|\]/g
来获取"["
, "]"
单词; 和.querySelector()
返回的匹配元素的.checked
属性
$(".checkbox").click(function () { var input = this.querySelector("input[type=checkbox]"); var _name = input.getAttribute("name").replace(/^\w+\[|\]/g, ""); var checked = input.checked; console.log(_name, checked); $.ajax(/* settings */); });