0

I need to check if a checkbox is checked or not in order to display an error message. So far I thought that this should work (if not checked than it should be empty I thought).

CODE

<span id="sc_info" style="float: right; padding-right: 5px;">

<input type="checkbox" name="terms" id="sc_terms" value="" checked="checked" />

<br /><label class="error" for="body" id="terms_error">This field is required.</label>
</form>

<script>
$(document).ready(function() {
    //Story Form
    $('.error').hide();  
    $(".button").click(function() {

    $('.error').hide();  
    var terms = $("input#sc_terms").val();  
    if (terms == "") {  //if is not checked
    $("label#terms_error").show();  //show error message
    $("input#sc_terms").focus(); //focus on an empty element
    return false;  
}  
});  
});
</script>

But this code doesn't work. can anyone suggest how to check if checkbox is checked?

2 Answers 2

4

Use jQuery's :checked selector:

if ($('#sc_terms').is(':checked')) {
    // Checkbox is checked, do stuff
}
else {
    // Checkbox is not checked, do stuff
    $("label#terms_error").show();  //show error message
    $("input#sc_terms").focus();
}

If you simply want to see if it's not checked:

if ($('#sc_terms:not(:checked)')) {
        // Checkbox is checked, do stuff
        $("label#terms_error").show();  //show error message
        $("input#sc_terms").focus();
 }

Note: Since you're using the ID selector, prefacing your selector with input or label is not necessary.

2

Something like:

if( $("input#sc_terms").is(":checked") )
     // is checked

And not checked:

if( $("input#sc_terms").is(":not(:checked)") )
     // not checked
2
  • .not is the opposite of .filter, and returns a jQuery object, which always passes the if clause.
    – pimvdb
    Commented Dec 5, 2011 at 20:05
  • for some reason it still shows error message in both cases, when it's checked and when it's not checked... if( $("input#sc_terms").not(":checked") ) { $("label#terms_error").show();
    – Ilja
    Commented Dec 5, 2011 at 20:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.