Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get checkbox value in jQuery

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

like image 786
maztt Avatar asked May 14 '10 13:05

maztt


People also ask

How can I get checkbox value in jQuery?

To get the value of the Value attribute you can do something like this: $("input[type='checkbox']"). val();

How can we get the value of selected checkboxes in a group using jQuery?

If you want to get checked checkboxes from a particular checkbox group, depending on your choice which button you have clicked, you can use $('input[name=”hobbies”]:checked') or $('input[name=”country”]:checked'). This will sure that the checked checkboxes from only the hobbies or country checkbox group are selected.

How do you get checkbox is checked or not in jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);


2 Answers

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 } 
like image 144
Sarfraz Avatar answered Sep 21 '22 13:09

Sarfraz


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" />
like image 35
Alain Tiemblo Avatar answered Sep 21 '22 13:09

Alain Tiemblo