tags:

views:

42

answers:

5

hi guys, I'm wondering why this simple switch isn't working.

the html of the checkbox is:

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

While the jquery inside a document(ready) is:

$j('#use_billing').change(function(){


    switch ($j(this).val())
    {

    case '1':

        $j('#gift_to').slideUp();

    break;

    default:

        $j('#gift_to').slideDown();
    break;
    }

});

If I check the box, my div id'd #gift_to does slideUp. Yet nothing happens on the uncheck... what am I missing?

+2  A: 

This will work. However, I am not sure why .val() doesn't work on checkboxes that are not checked.

$j('#use_billing').change(function(){

    if ($(this).is(":checked")) {
        $j('#gift_to').slideUp();
    } else {
        $j('#gift_to').slideDown();
    }
});
jessegavin
+1  A: 

Use this code instead and see if it works

$('#use_billing').change(function(){
  if($(this).is(":checked")){
     $('#gift_to').slideUp();
  } else {
     $('#gift_to'). slideDown();
  }
});
GeekTantra
+3  A: 

You should call is(':checked').

For example:

if($j(this).is(':checked'))
    $j('#gift_to').slideUp();
else
    $j('#gift_to').slideDown();

Or, if you want to be clever,

$j('#gift_to')[$j(this).is(':checked') ? 'slideUp' : 'slideDown']();
SLaks
woah that is some hardcore shorthand there Slaks. thanks!
cosmicbdog
+1  A: 

Since no one has actually explained why: The value of the checkbox is ALWAYS "1", regardless of the input being checked or not. It's the checked state that's changing as SLaks, jessegavin & GeekTantra have pointed out.

Ben Rowe
thanks for clarifying Ben
cosmicbdog
+1  A: 

The value attribute of your element will be always "1" regardless if it's checked or not.

I would recommend you simply to look at the checked attribute, rather than invoking the .is method with the :checked selector as everyone suggested:

$j('#use_billing').change(function(){
  if (this.checked) {
    $j('#gift_to').slideUp();
    return;
  }
  $j('#gift_to').slideDown();
})

Or simply:

$j('#use_billing').change(function(){
  $j('#gift_to')[this.checked ? 'slideUp' : 'slideDown']();
});
CMS