tags:

views:

64

answers:

5

Hi,

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

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

if ( checked.length && checked.val().length ) {
   // do something with checked
}
meder
@meder - Just a note. If I remember correctly, placing the tag name before an ID will actually slow down the selector.
patrick dw
I don't think anyone cares about the performance of something so trivial. No one would really notice.
meder
@meder - With all due respect, nonsense. Performance is always important with selectors. You are negating the benefit of using an ID when you place the tag name before. If it is so trivial, then why use IDs at all? It is a bad practice that shouldn't be perpetuated.
patrick dw
@meder - ...to further illustrate, you cached the jQuery object so you wouldn't have to run the selector twice. Running the selector twice *without* the tag in the selector can be faster than running it once *with* the tag in the selector. Ok, I'm done now. :o)
patrick dw
The difference is in nano/milliseconds unless you're doing it hundreds of times in a loop. You will *not* notice it.
meder
+1  A: 

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 {
}
Walter Mundt
`checked` property doesn't exist on the jQuery object so that will always fail unless you do `[0].checked`
meder
oh yeah that's what I mean, just checked or not! thanks
Good catch, meder; serves me right for not testing. Is that better?
Walter Mundt
+1  A: 

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

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

}
Khnle
+2  A: 

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/

patrick dw
+2  A: 

Even easier

if($('#foo').is(':checked')){
    //code here
}
Dmitri Farkov
Don't place the tag name `input` before an ID. It slows down the selector.
patrick dw
Edited, thanks Patrick!
Dmitri Farkov