Get checkbox value in jQuery

2019-01-01 12:02发布

How can I get a checkbox's value in jQuery?

15条回答
路过你的时光
2楼-- · 2019-01-01 12:28
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);
    });
查看更多
梦寄多情
3楼-- · 2019-01-01 12:29
$('#checkbox_id').val();
$('#checkbox_id').is(":checked");
$('#checkbox_id:checked').val();
查看更多
孤独寂梦人
4楼-- · 2019-01-01 12:31

Those 2 ways are working:

  • $('#checkbox').prop('checked')
  • $('#checkbox').is(':checked') (thanks @mgsloan)

$('#test').click(function() {
    alert("Checkbox state (method 1) = " + $('#test').prop('checked'));
    alert("Checkbox state (method 2) = " + $('#test').is(':checked'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Check me: <input id="test" type="checkbox" />

查看更多
一个人的天荒地老
5楼-- · 2019-01-01 12:34

Simple but effective and assumes you know the checkbox will be found:

$("#some_id")[0].checked;

Gives true/false

查看更多
栀子花@的思念
6楼-- · 2019-01-01 12:36

Just attention, as of today, 2018, due to api changing over the years. removeAttr are depricated, NOT working anymore!

Jquery Check or unCheck a checkbox:

Bad, not working any more.

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

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

Instead you should do:

      $('#add_user_certificate_checkbox').prop('checked', true);
      $('#add_user_certificate_checkbox').prop('checked', false);
查看更多
流年柔荑漫光年
7楼-- · 2019-01-01 12:38
<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>
查看更多
登录 后发表回答