如何在jQuery中获得复选框的值?


当前回答

最好的方法是$('input[name="line"]:checked').val()

你也可以得到select text $('input[name="line"]:checked').text()

为单选按钮输入添加值属性和名称。确保所有输入都具有相同的name属性。

<div class="col-8 m-radio-inline">
    <label class="m-radio m-radio-filter">
        <input type="radio" name="line" value="1" checked> Value Text 1
    </label>
    <label class="m-radio m-radio-filter">
        <input type="radio" name="line" value="2"> Value Text 2
    </label>
    <label class="m-radio m-radio-filter">
        <input type="radio" name="line" value="3"> Value Text 3
    </label>
</div>

其他回答

你可以用下面的。经过测试,它工作正常。

$('#checkbox_id').is(":checked"); // jQuery

如果选中复选框,则返回true,反之亦然。

下面的代码片段适用于任何试图用JavaScript做同样事情的人。

document.getElementById("checkbox_id").checked //JavaScript

如果选中复选框,则返回true

在jquery中获取checkboxex的值:

var checks = $("input[type='checkbox']:checked"); // returns object of checkeds.

for(var i=0; i<checks.length; i++){
    console.log($(checks[i]).val()); // or do what you want
});

在pure js中:

var checks = document.querySelectorAll("input[type='checkbox']:checked");

for(var i=0; i<checks.length; i++){
    console.log(checks[i].value); // or do what you want
});
jQuery(".checkboxClass").click(function(){
        var selectedCountry = new Array();
        var n = jQuery(".checkboxClass:checked").length;
        if (n > 0){
            jQuery(".checkboxClass:checked").each(function(){
                selectedCountry.push($(this).val());
            });
        }
        alert(selectedCountry);
    });

要获取value属性的值,你可以这样做:

$("input[type='checkbox']").val();

或者如果你已经为它设置了一个类或id,你可以:

$('#check_id').val();
$('.check_class').val();

然而,无论是否检查,都会返回相同的值,这可能会令人困惑,因为它与提交的表单行为不同。

要检查是否已检查,请执行以下操作:

if ($('#check_id').is(":checked"))
{
  // it is checked
}

请注意,截至今天,2018年,由于api多年来不断变化。 removeAttr已被撤销,不再工作!

Jquery选中或取消选中复选框:

糟糕,再也不能工作了。

   $('#add_user_certificate_checkbox').removeAttr("checked");

   $('#add_user_certificate_checkbox').attr("checked","checked");

相反,你应该这样做:

      $('#add_user_certificate_checkbox').prop('checked', true);
      $('#add_user_certificate_checkbox').prop('checked', false);