测试是否使用jQuery选中了复选框

本文翻译自: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();

you can test here 你可以在这里测试一下


#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;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章