How can i use switch to have a checkbox checked in jQuery?
I am trying to use switch() if the check box is checked,but it does not work. What is the probem here i could not figure out. Could you help plz. here is what i tried
<input type="checkbox" class="che" valu开发者_StackOverflowe="1" />age
<input type="checkbox" class="che" value="2" />sex
$(".che").click(function(){
var chek= $(this).is(":checked") ;
alert(chek);
switch(chek){
case 1:
alert ('ok');
$('.myTableRow').show();
break;
case 2:
alert('hora');
$(".myTableRow").hide();
break;
}
});
chek
is a boolean value. It will never be equal to 2
(false
is equivalent to 0
and true
to 1
), so case 2:
will never be reached.
If you want to get the value of the checkbox, you have to call val()
:
$(".che").change(function(){
var chek= $(this).val();
alert(chek);
switch(chek){
case "1":
alert ('ok');
$('.myTableRow').show();
break;
case "2":
alert('hora');
$(".myTableRow").hide();
break;
}
});
But this setup does not seem to be logical. What should happen if both boxes are selected? It will always execute the action of the last selected checkbox.
Maybe you just want:
$(".che").change(function(){
$('.myTableRow').toggle(this.checked); // or !this.checked
});
Although this is not really better.
You have to think about how your form should work before you implement any logic.
Reference: change
, toggle
精彩评论