[javascript] Testing if a checkbox is checked with jQuery

If the checkbox is checked, then I only need to get the value as 1; otherwise, I need to get it as 0. How do I do this using jQuery?

$("#ans").val() will always give me one right in this case:

<input type="checkbox" id="ans" value="1" />

This question is related to javascript jquery checkbox jquery-selectors

The answer is


You can also use:

$("#ans:checked").length == 1;

Use:

$("#ans option:selected").val()

I've came through a case recently where I've needed check value of checkbox when user clicked on button. The only proper way to do so is to use prop() attribute.

var ansValue = $("#ans").prop('checked') ? $("#ans").val() : 0;

this worked in my case maybe someone will need it.

When I've tried .attr(':checked') it returned checked but I wanted boolean value and .val() returned value of attribute value.


You can perform it, this way:

$('input[id=ans]').is(':checked');     

I've found the same problem before, hope this solution can help you. first, add a custom attribute to your checkboxes:

<input type="checkbox" id="ans" value="1" data-unchecked="0" />

write a jQuery extension to get value:

$.fn.realVal = function(){
    var $obj = $(this);
    var val = $obj.val();
    var type = $obj.attr('type');
    if (type && type==='checkbox') {
        var un_val = $obj.attr('data-unchecked');
        if (typeof un_val==='undefined') un_val = '';
        return $obj.prop('checked') ? val : un_val;
    } else {
        return val;
    }
};

use code to get check-box value:

$('#ans').realVal();

you can test here


There are Several options are there like....

 1. $("#ans").is(':checked') 
 2. $("#ans:checked")
 3. $('input:checkbox:checked'); 

If all these option return true then you can set value accourdingly.


// use ternary operators
$("#ans").is(':checked') ? 1 : 0;

First check the value is checked

$("#ans").find("checkbox").each(function(){
    if ($(this).prop('checked')==true){ 
    var id = $(this).val()
    }
});

Else set the 0 value


$("#ans").attr('checked') 

will tell you if it's checked. You can also use a second parameter true/false to check/uncheck the checkbox.

$("#ans").attr('checked', true);

Per comment, use prop instead of attr when available. E.g:

$("#ans").prop('checked')

You can get value (true/false) by these two method

$("input[type='checkbox']").prop("checked");
$("input[type='checkbox']").is(":checked");

If you want integer value of checked or not, try:

$("#ans:checked").length

Try this

$('input:checkbox:checked').click(function(){
    var val=(this).val(); // it will get value from checked checkbox;
})

Here flag is true if checked otherwise false

var flag=$('#ans').attr('checked');

Again this will make cheked

$('#ans').attr('checked',true);

 $("#id").prop('checked') === true ? 1 : 0;

function chkb(bool){
if(bool)
return 1;
return 0;
}

var statusNum=chkb($("#ans").is(':checked'));

statusNum will equal 1 if the checkbox is checked, and 0 if it is not.

EDIT: You could add the DOM to the function as well.

function chkb(el){
if(el.is(':checked'))
return 1;
return 0;
}

var statusNum=chkb($("#ans"));

<input type="checkbox" id="ans" value="1" />

Jquery : var test= $("#ans").is(':checked') and it return true or false.

In your function:

$test =($request->get ( 'test' )== "true")? '1' : '0';

Stefan Brinkmann's answer is excellent, but incomplete for beginners (omits the variable assignment). Just to clarify:

// this structure is called a ternary operator
var cbAns = ( $("#ans").is(':checked') ) ? 1 : 0;

It works like this:

 var myVar = ( if test goes here ) ? 'ans if yes' : 'ans if no' ;

Example:

var myMath = ( 1 > 2 ) ? 'yes' : 'no' ;
alert( myMath );

Alerts 'no'

If this is helpful, please upvote Stefan Brinkmann's answer.


Just use $(selector).is(':checked')

It returns a boolean value.


You can try this:

$('#studentTypeCheck').is(":checked");

$('input:checkbox:checked').val();        // get the value from a checked checkbox

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

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

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value