user246114
user246114

Reputation: 51611

Get value of a checkbox?

I have a checkbox, how do I get its value using jquery? I have this example from searching:

var checked = $('input[type=checkbox]:checked').val() != undefined;

but how do I specify which checkbox I'm interested in, I want to only examine a checkbox with a particular id?

Thanks

Upvotes: 3

Views: 576

Answers (5)

Dmitri Farkov
Dmitri Farkov

Reputation: 9671

Even easier

if($('#foo').is(':checked')){
    //code here
}

Upvotes: 6

meder omuraliev
meder omuraliev

Reputation: 186562

var checked = $('input#foo:checked');

if ( checked.length && checked.val().length ) {
   // do something with checked
}

Upvotes: 2

user113716
user113716

Reputation: 322492

You can use jQuery's is() along with the :checked selector:

var $theCheckbox = $('#theID');

if( $theCheckbox.is(':checked') ) {
    var checked = $theCheckbox.val();
}

http://jsfiddle.net/BYagp/1/

Upvotes: 2

Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10857

Let's say your id is #myid, then:

var checked = $('input[type="checkbox"]#myid').attr('checked');
if (checked) {
   //box is checked
} else {

}

Upvotes: 1

Walter Mundt
Walter Mundt

Reputation: 25271

What do you mean by value? You can tell whether a box is checked with the checked attribute. If it's checked, the value it sends to the server if the form submitted is in the value attribute.

var mybox = $('input#myid');
if (mybox.length > 0 && mybox[0].checked) {
    // do something, or use mybox[0].value
} else {
}

Upvotes: 1

Related Questions