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?
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.
Something like:
if( $("input#sc_terms").is(":checked") )
// is checked
And not checked:
if( $("input#sc_terms").is(":not(:checked)") )
// not checked
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.