0

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);
}
DIF
  • 2,470
  • 6
  • 35
  • 49
user1248589
  • 43
  • 1
  • 4
  • 1
    Is 'FALSE' capitalized in your actual code? That most likely isn't it but I'm curious... Otherwise I have an idea. – nmagerko Mar 04 '12 at 20:25
  • 1
    `CHECKBOX` is not the right selector. Even if it's correct, you have to use `$('CHECKBOX').is(':checked');`. – Rob W Mar 04 '12 at 20:26
  • Possible duplicate of [How do I check if a checkbox is checked in jQuery?](http://stackoverflow.com/questions/901712/how-do-i-check-if-a-checkbox-is-checked-in-jquery) – Heretic Monkey Dec 14 '16 at 17:02

4 Answers4

0

Try using:

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

or:

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

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

imm
  • 5,837
  • 1
  • 26
  • 32
0
$('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
0

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)
kumiau
  • 714
  • 3
  • 17
0
`$('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. e.g. 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.

RobG
  • 142,382
  • 31
  • 172
  • 209