本文翻譯自:Testing if a checkbox is checked with jQuery
If the checkbox is checked, then I only need to get the value as 1; 如果選中該複選框,那麼我只需要將值設爲1; otherwise, I need to get it as 0. How do I do this using jQuery? 否則,我需要將其設爲0.如何使用jQuery執行此操作?
$("#ans").val()
will always give me one right in this case: $("#ans").val()
在這種情況下總是給我一個權利:
<input type="checkbox" id="ans" value="1" />
#1樓
參考:https://stackoom.com/question/KC8Z/測試是否使用jQuery選中了複選框
#2樓
Just use $(selector).is(':checked')
只需使用$(selector).is(':checked')
It returns a boolean value. 它返回一個布爾值。
#3樓
I've found the same problem before, hope this solution can help you. 我之前發現了同樣的問題,希望這個解決方案可以幫到你。 first, add a custom attribute to your checkboxes: 首先,在複選框中添加自定義屬性:
<input type="checkbox" id="ans" value="1" data-unchecked="0" />
write a jQuery extension to get value: 編寫一個jQuery擴展來獲取值:
$.fn.realVal = function(){
var $obj = $(this);
var val = $obj.val();
var type = $obj.attr('type');
if (type && type==='checkbox') {
var un_val = $obj.attr('data-unchecked');
if (typeof un_val==='undefined') un_val = '';
return $obj.prop('checked') ? val : un_val;
} else {
return val;
}
};
use code to get check-box value: 使用代碼獲取複選框值:
$('#ans').realVal();
#4樓
function chkb(bool){
if(bool)
return 1;
return 0;
}
var statusNum=chkb($("#ans").is(':checked'));
statusNum will equal 1 if the checkbox is checked, and 0 if it is not. 如果選中該複選框,statusNum將等於1,如果不是,則爲0。
EDIT: You could add the DOM to the function as well. 編輯:您也可以將DOM添加到該函數中。
function chkb(el){
if(el.is(':checked'))
return 1;
return 0;
}
var statusNum=chkb($("#ans"));
#5樓
Try this 試試這個
$('input:checkbox:checked').click(function(){
var val=(this).val(); // it will get value from checked checkbox;
})
Here flag is true if checked otherwise false 如果選中則返回false,則此標誌爲true
var flag=$('#ans').attr('checked');
Again this will make cheked 再次,這將使cheked
$('#ans').attr('checked',true);
#6樓
// use ternary operators
$("#ans").is(':checked') ? 1 : 0;