嗨,经过大量搜索后,我找到了一种检查复选框的方法。但我不知道是什么问题。它的 val() 总是返回on。当我检查它以及取消选中它时,就会发生这种情况。我想它应该在未选中时返回null。帮助
$(document).ready(function(){
$('#ch').change(function(){
alert($(this).val());
});
});
和html
<input type="checkbox" id="ch"/> Check it out...
嗨,经过大量搜索后,我找到了一种检查复选框的方法。但我不知道是什么问题。它的 val() 总是返回on。当我检查它以及取消选中它时,就会发生这种情况。我想它应该在未选中时返回null。帮助
$(document).ready(function(){
$('#ch').change(function(){
alert($(this).val());
});
});
和html
<input type="checkbox" id="ch"/> Check it out...
您有一组选项来检查您checkbox
是选中还是未选中,
alert($(this).is(":checked")); ////return true if checked
或者
alert(this.checked); //return true if checked
或者
<input type="checkbox" id="ch" checked/>
alert($(#ch).attr( "checked")); //return checked if checked
或者
alert($(this).prop( "checked")); //return true if checked
你可以这样做:
alert($(this).prop('checked'));
或者如果您想获取复选框的值,则需要添加value
属性,例如:
<input type="checkbox" value="your_value" id="ch"/> Check it out...
和js
$('#ch').change(function(){
alert($(this).val()); //gives you 'your_value' in any case
});
$(this)
是一个 jQuery 集合,您可以使用 jQuery 方法获取相关数据,如果您想使用.checked
,您可以执行以下任一操作:
this.checked
//or
$(this)[0].checked
这意味着:
$(this)[0] == this
演示:: jsFiddle
尝试:
$(document).ready(function(){
$('#ch').change(function(){
alert($(this).is(':checked'));
});
});
你需要给你的表单对象一个值属性.Val()
来返回你可以使用的东西:
<input type="checkbox" value="some_usefull_value" id="ch"/>