Hi there, I am not entirely sure how to target checkboxes with jquery. I had a look around but the methods indicated don't seem to work for me for whatever reason.
Given the following html fragment:
...
<form>
<input type="checkbox" value="red" name="the_color" checked="checked" id="red"><label for="red">This is red</label><br>
<input type="checkbox" value="blue" name="the_color" checked="checked" id="blue"><label for="blue">This is blue</label><br>
...
I need to target each check box and if unchecked do something. So in my javascript I have
$("#red").click(function(){//targets the first tickbox by id
color();
});
function color(){
var isChecked = $(this);
if(isChecked.is(":checked")){
alert("Checked");
}
else{
alert("Unchecked");
}
}
But this doesn't work. I thought I could target checkboxes by ID. Nevermind, I tried this instead:
$("input:checkbox[name='the_color']").click(function(){
color();
});
function color(){
var isChecked = $(this);
if(isChecked.is(":checked")){
alert("Checked");
}
else{
alert("Unchecked");
}
}
But no joy either. So I wonder, what selector will actually select a specific check box in the above html?
Also, besides the selector, is the way to check whether a checkbox is checked or not correct?
thanks