views:

25

answers:

2
<input type="checkbox" name="feature1" value="0" />

If checked, value="1"; else value="0";

if ( $('input[name=feature1]').is(':checked') ) {
  $('input[name=feature1]').val('1');
}

I think the above jQuery may work, but its one-time check, how do I make it that everytime the checkbox is clicked/checked, value becomes 1, else 0?

Many thanks

+1  A: 
$('input[name=feature1]').click(function(){
    if ($(this).is(':checked') ) {
      $(this).val('1');
    } else {
      $(this).val('0');
    }
});

or

$('input[name=feature1]').click(function(){
    if (this.checked) {
      $(this).val('1');
    } else {
      $(this).val('0');
    }
});

or

much better

$('input[name=feature1]').click(function(){
      $(this).val(this.checked ? 1:0);
});

and just as I thought there is still a much better way..

$('input[name=feature1]').click(function(){
      this.value = this.checked ? 1:0;      
});​
Reigel
Yes, but this is one-time check, not a toggle. no?
Nimbuz
you caught me editing..
Reigel
Awesome, the one works like a charm. Just wondering if it'd work with multiple elements $('one, two, three').. ?
Nimbuz
yes, sure it will...
Reigel
+1  A: 

I'd give the input an ID, just to make it a bit easier to write your jQuery - for the purposes of this answer I'll pretend we've duplicated the name.

jQuery("#feature1").click(function() {
   if (this.checked) {
      jQuery(this).val(1);
   } else {
      jQuery(this).val(0);
   }
});
Gareth Midwood
One question though - why do you need to set a value on it? If you're using PHP then the value will only be submitted if the checkbox is checked, you just need to check it isset() to get a value..
Gareth Midwood