jQuery 获取复选框值(如果选中)并在未选中时删除值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17717608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery get checkbox value if checked and remove value when unchecked
提问by JS-Hero
jQuery function to get checkbox value if checked and remove value if unchecked.
jQuery 函数在选中时获取复选框值,如果未选中则删除值。
<input type="checkbox" id="check" value="3" />hiiii
<div id="show"></div>
function displayVals(){
var check = $('#check:checked').val();
$("#show").html(check);
}
var qqqq = window.setInterval( function(){
displayVals()
},
10
);
回答by adeneo
You don't need an interval, everytime someone changes the checkbox the change
event is fired, and inside the event handler you can change the HTML of #show
based on wether or not the checkbox was checked :
您不需要间隔,每次有人更改复选框时change
都会触发事件,并且在事件处理程序中,您可以#show
根据复选框是否被选中来更改 HTML :
$('#check').on('change', function() {
var val = this.checked ? this.value : '';
$('#show').html(val);
});
回答by Tushar Gupta - curioustushar
Working Demo http://jsfiddle.net/cse_tushar/HvKmE/5/
工作演示http://jsfiddle.net/cse_tushar/HvKmE/5/
js
js
$(document).ready(function(){
$('#check').change(function(){
if($(this).prop('checked') === true){
$('#show').text($(this).attr('value'));
}else{
$('#show').text('');
}
});
});
回答by Mahdy Aslamy
There is another way too:
还有一种方法:
Using the new property method will return true or false.
$('#checkboxid').prop('checked');
Using javascript without libs
document.getElementById('checkboxid').checked
Using the JQuery's is()
$("#checkboxid").is(':checked')
Using attr to get checked
$("#checkboxid").attr("checked")
使用新的属性方法将返回 true 或 false。
$('#checkboxid').prop('checked');
在没有库的情况下使用 javascript
document.getElementById('checkboxid').checked
使用 JQuery 的 is()
$("#checkboxid").is(':checked')
使用 attr 进行检查
$("#checkboxid").attr("checked")
i prefer second option.
我更喜欢第二种选择。