如何在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>

其他回答

使用以下代码:

$('input[name^=CheckBoxInput]').val();
$('.class[value=3]').prop('checked', true);
//By each()
var testval = [];
 $('.hobbies_class:checked').each(function() {
   testval.push($(this).val());
 });


//by map()
var testval = $('input:checkbox:checked.hobbies_class').map(function(){
return this.value; }).get().join(",");

 //HTML Code

 <input type="checkbox" value="cricket" name="hobbies[]"  class="hobbies_class">Cricket 
  <input type="checkbox" value="hockey" name="hobbies[]" class="hobbies_class">Hockey

例子 演示

这两种方法是有效的:

$(" #复选框”).prop(检查) $('#复选框').is(':checked')(谢谢@mgsloan)

$(" #测试”).click(函数(){ alert("复选框状态(方法1)= " + $('#test').prop('checked')); alert("复选框状态(方法2 ) = " + $('# 测试的).(':检查')); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js " > < /脚本> 检查我:<input id="test" type="checkbox" />

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