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


当前回答

//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

例子 演示

其他回答

在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
});

如果只期望选择一个子元素:

form.querySelector(":checked").value
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);
    });

使用以下代码:

$('input[name^=CheckBoxInput]').val();
<script type="text/javascript">
$(document).ready(function(){
    $('.laravel').click(function(){
        var val = $(this).is(":checked");
        $('#category').submit();
    });
});

<form action="{{route('directory')}}" method="post" id="category">
                        <input type="hidden" name="_token" value="{{ csrf_token() }}">
                        <input name="category" value="{{$name->id}}"  class="laravel" type="checkbox">{{$name->name}}
                      </form>