[jquery] Get checkbox value in jQuery

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

This question is related to jquery html forms checkbox

The answer is


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

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

Gives true/false


Those 2 ways are working:

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

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


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

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

_x000D_
_x000D_
var checkbox = document.querySelector('input[type="checkbox"]');_x000D_
_x000D_
alert(checkbox.checked);
_x000D_
<input type="checkbox"/>
_x000D_
_x000D_
_x000D_


Here is a quick example listening to the change event:

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


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

_x000D_
_x000D_
var elements = document.querySelectorAll('input[type="checkbox"]:checked');_x000D_
var checkedElements = Array.prototype.map.call(elements, function (el, i) {_x000D_
    return el.name;_x000D_
});_x000D_
_x000D_
console.log(checkedElements);
_x000D_
<div class="parent">_x000D_
    <input type="checkbox" name="name1" />_x000D_
    <input type="checkbox" name="name2" />_x000D_
    <input type="checkbox" name="name3" checked="checked" />_x000D_
    <input type="checkbox" name="name4" checked="checked" />_x000D_
    <input type="checkbox" name="name5" />_x000D_
</div>
_x000D_
_x000D_
_x000D_


Try this small solution:

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

or

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

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

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

to get value of checked checkboxex in jquery:

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

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

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

$('.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

Example
Demo


The best way 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.getAttribute("checked") or elem.prop("defaultChecked").

Please note that elem.attr("checked") is modified only after version 1.6.1+ of jQuery to return the same result as elem.prop("checked").

Some answers are misleading or imprecise, Please check below yourself:

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


Use the following code:

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

Just to clarify things:

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

Will return 'true' or 'false'


Best way is $('input[name="line"]:checked').val()

And also you can get selected text $('input[name="line"]:checked').text()

Add value attribute and name to your radio button inputs. Make sure all inputs have same name attribute.

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

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

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to checkbox

Setting default checkbox value in Objective-C? Checkbox angular material checked by default Customize Bootstrap checkboxes Angular ReactiveForms: Producing an array of checkbox values? JQuery: if div is visible Angular 2 Checkbox Two Way Data Binding Launch an event when checking a checkbox in Angular2 Checkbox value true/false Angular 2: Get Values of Multiple Checked Checkboxes How to change the background color on a input checkbox with css?