简体   繁体   中英

Check if a checkbox is checked in JS

I am new to js and jquery. Currently, I have a form at form.php which contains a checkbox. When the user clicks submit, the form variables are sent to a form.js file where each value is checked to be null or not.

The form.js file works perfectly, however, for the checkbox nothing seems to happen. I have a feeling this is due to the way I have declared the variable.

The following is the code for the js file:

var email = $('#email').val();
var website = $('#website').val();
var CHECKBOX = $('CHECKBOX').val();
...
...
if (CHECKBOX.checked == FALSE){
    var error = true;
    $('#notchecked_error').fadeIn(500);
}else{
    $('#notchecked_error').fadeOut(500);
}

Try using:

if ( $('#CHECKBOX').prop("checked") )

or:

if ( $('#CHECKBOX').is(":checked") )

Also, be sure your selector for the checkbox is correct.

$('input[type=checkbox]:checked') // If you have multiple checkboxes you can use this and loop through them to get additional info
$('#checkboxID:checked').length // To get one specific checkbox

I see two problems in your code. The first one is that the selector in your CHECKBOX assignation is faulty. It should be

var CHECKBOX = $('#CHECKBOX').val();

or

var CHECKBOX = $('input[type=checkbox]').val();

the second problem is that you are reading CHECKBOX.checked from the val() function, you need to read it from the checkbox itself.

if(CHECKBOX.checked)
`$('CHECKBOX').val();`

Will try to find an element with a tagname of CHECKBOX and return it's value. Presumably you want to reference the checkbox with an ID of CHECKBOX :

var CHECKBOX = $('#CHECKBOX');

To see if it's checked:

if (!CHECKBOX[0].checked) {
  // CHECKBOX is not checked
}

You really should learn basic javascript before using jQuery. Usually validation is initiated from a form submit, which can give you are reference to the form. You can then reference all of the form elements as properties of the form, you don't need to create all of those jQuery objects. eg if you form is something like:

<form ... onsubmit="validate(this)"... >
  <input type="checkbox" name="checkbox">
</form>

Then in your validate function:

function validate(form) {
  if (!form.checkbox.checked) {
    // the checkbox isn't checked
  }
}

You can attach the listener dynamically if you wish.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM