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.

Sign up to request clarification or add additional context in comments.

Comments

2

Something like:

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

And not checked:

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

2 Comments

.not is the opposite of .filter, and returns a jQuery object, which always passes the if clause.
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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.