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

Member Avatar for LastMitch

So I wonder, what selector will actually select a specific check box in the above html?

You can try this (I assume you already figure this out from another member who was helping you with this):

$("#red").click(function(){//targets the first tickbox by id
color(id);
});

function color(id) {
alert(id);
var checked = $('#' + id).is(":checked").length;
alert(checked);

if (checked == 0) {
return false;
} else {
return true;
}
}

<fieldset id="check">
<input type="checkbox" value="red" name="chk[]" id="red"><label for="red">This is red</label>
</fieldset>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.