check whether checkbox is checked or not using jquery

gautamlakum picture gautamlakum · Oct 27, 2010 · Viewed 38.4k times · Source

I want to check whether checkbox is checked or not using jquery. I want to check it on checkbox's onclick event.

<input type="checkbox" onclick="javascript:check_action();" id="Public(Web)" checked="checked" value="anyone" name="data[anyone]">

Is it possible? How?

Thanks.

Answer

Tim Down picture Tim Down · Oct 27, 2010

First, don't use javascript: in event handler attributes. It's wrong and only works because it happens to be valid JavaScript syntax. Second, your id is not valid. Parentheses are not allowed in the id attribute (in HTML 4 at least; HTML 5 lifts this restriction). Third, if you're using jQuery it probably makes sense to use its click() method to handle the click event, although be aware that changing it to do that will mean that if the user clicks on the checkbox before the document has loaded then your script won't handle it.

<input type="checkbox" id="Public_Web" checked value="anyone"
    name="data[anyone]">

$(document).ready(function() {
    $("#Public_Web").click(function() {
        if (this.checked) {
            alert("Checked!");
        }
    });
});