Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple JavaScript Checkbox Validation

I usually work with PHP so sadly don't have some basic JS principles down. This is all I want to accomplish--I've seen many posts on this topic but they are usually beyond what I need.

Here is my form:

 <input type="checkbox" name="checkbox" value="check"  />
 <input type="submit" name="email_submit" value="submit" onclick="----??----"  />

The checkbox is a simple "I agree". I want the submit button to be pressed and it will only submit if that check box is selected.

Here's the thing: I want the simple, cheating way -- no methods -- just some inline code in that form (assuming its not overly long?). This is not a public page, I just need something quick and simple with that type of validation. If its unchecked, it will throw an alert(); if its checked it will submit via post through php and go on as normal.

like image 983
TheLettuceMaster Avatar asked Jun 27 '12 20:06

TheLettuceMaster


People also ask

How do I validate a checkbox?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.


2 Answers

You could use:

 if(!this.form.checkbox.checked)
{
    alert('You must agree to the terms first.');
    return false;
}

(demo page).

<input type="checkbox" name="checkbox" value="check"  />
<input type="submit" name="email_submit" value="submit" onclick="if(!this.form.checkbox.checked){alert('You must agree to the terms first.');return false}"  />
  • Returning false from an inline event handler will prevent the default action from taking place (in this case, submitting the form).
  • ! is the Boolean NOT operator.
  • this is the submit button because it is the element the event handler is attached to.
  • .form is the form the submit button is in.
  • .checkbox is the control named "checkbox" in that form.
  • .checked is true if the checkbox is checked and false if the checkbox is unchecked.
like image 140
PleaseStand Avatar answered Sep 29 '22 12:09

PleaseStand


For now no jquery or php needed. Use just "required" HTML5 input attrbute like here

 <form>
        <p>
            <input class="form-control" type="text" name="email" />
            <input type="submit" value="ok" class="btn btn-success" name="submit" />
            <input type="hidden" name="action" value="0" />
        </p>
        <p><input type="checkbox" required name="terms">I have read and accept <a href="#">SOMETHING Terms and Conditions</a></p>
 </form>

This will validate and prevent any submit before checkbox is opt in. Language independent solution because its generated by users web browser.

like image 39
PrestaShark Avatar answered Sep 29 '22 11:09

PrestaShark