Get checkbox value in jQuery

2019-01-01 12:11发布

问题:

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

回答1:

To get the value of the Value attribute you can do something like this:

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

Or if you have set a class or id for it, you can:

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

However this will return the same value whether it is checked or not, this can be confusing as it is different to the submitted form behaviour.

To check whether it is checked or not, do:

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


回答2:

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



回答3:

Try this small solution:

$(\"#some_id\").attr(\"checked\") ? 1 : 0;

or

$(\"#some_id\").attr(\"checked\") || 0;


回答4:

The only correct ways of retrieving a checkbox\'s value is as following

if ( elem.checked ) 
if ( $( elem ).prop( \"checked\" ) ) 
if ( $( elem ).is( \":checked\" ) ) 

as explained in the official documentations in jQuery\'s website. The rest of the methods has nothing to do with the property of the checkbox, they are checking the attribute which means they are testing the initial state of the checkbox when it was loaded. So in short:

  • When you have the element and you know it is a checkbox you can simply read its property and you won\'t need jQuery for that (i.e. elem.checked) or you can use $(elem).prop(\"checked\") if you want to rely on jQuery.
  • If you need to know (or compare) the value when the element was first loaded (i.e. the default value) the correct way to do it is $(elem).is(\":checked\").

Answers are misleading, Please check below yourself:

http://api.jquery.com/prop/



回答5:

Just to clarify things:

$(\'#checkbox_ID\').is(\":checked\")

Will return \'true\' or \'false\'



回答6:

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


回答7:

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


回答8:

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

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

Gives true/false



回答9:

Despite the fact that this question is asking for a jQuery solution, here is a pure JavaScript answer since nobody has mentioned it.

Without jQuery:

Simply select the element and access the checked property (which returns a boolean).

var checkbox = document.querySelector(\'input[type=\"checkbox\"]\');

alert(checkbox.checked);
<input type=\"checkbox\"/>


Here is a quick example listening to the change event:

var checkbox = document.querySelector(\'input[type=\"checkbox\"]\');
checkbox.addEventListener(\'change\', function (e) {
    alert(this.checked);
});
<input type=\"checkbox\"/>


To select checked elements, use the :checked pseudo class (input[type=\"checkbox\"]:checked).

Here is an example that iterates over checked input elements and returns a mapped array of the checked element\'s names.

Example Here

var elements = document.querySelectorAll(\'input[type=\"checkbox\"]:checked\');
var checkedElements = Array.prototype.map.call(elements, function (el, i) {
    return el.name;
});

console.log(checkedElements);

var elements = document.querySelectorAll(\'input[type=\"checkbox\"]:checked\');
var checkedElements = Array.prototype.map.call(elements, function (el, i) {
    return el.name;
});

console.log(checkedElements);
<div class=\"parent\">
    <input type=\"checkbox\" name=\"name1\" />
    <input type=\"checkbox\" name=\"name2\" />
    <input type=\"checkbox\" name=\"name3\" checked=\"checked\" />
    <input type=\"checkbox\" name=\"name4\" checked=\"checked\" />
    <input type=\"checkbox\" name=\"name5\" />
</div>



回答10:

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

Example
Demo



回答11:

Here is how to get the value of all checked checkboxes as an array:

var values = (function() {
                var a = [];
                $(\".checkboxes:checked\").each(function() {
                    a.push(this.value);
                });
                return a;
            })()


回答12:

$(\'.class[value=3]\').prop(\'checked\', true);



回答13:

Use the following code:

$(\'input[name^=CheckBoxInput]\').val();


回答14:

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


回答15:

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