简体   繁体   中英

Onsubmit, check number of checkboxes checked

I think my brain has already checked out and is in holiday mode. I'm trying to do something extremely simple, and I can not get it to work for the life of me.

I have a form that is dynamically generated via server-side code. It can have one or more questions that have checkboxes as options. I need to check to make sure at least one item is checked in any group, and the validation has to be done in pure JS (no jQuery).

I'm banging my head against the desk trying to get it to work:

HTML:

<form onsubmit="return validateCheckboxes();">
<h4>Which things do you enjoy?</h4>

<input type='checkbox' name='2' value='12' id='2_12'>
<label for='2_12'>&nbsp;&nbsp;Breathing</label><br />

<input type='checkbox' name='2' value='13' id='2_13'>
<label for='2_13'>&nbsp;&nbsp;Watching paint dry</label><br />

<input type='checkbox' name='2' value='14' id='2_14'>
<label for='2_14'>&nbsp;&nbsp;Nothing</label><br />
<br />
<br />
<input type="button" value="Submit">

Javascript:

function validateCheckboxes() {
   if (document.querySelector('.2:checked')) {
        alert('something is checked');
        return true;
   } else {
        alert('NOTHING is checked');
        return false;
   }
};

jsFiddle Link: https://jsfiddle.net/r6c4hxhj/

The selector .2:checked is looking for class="2" in the checkboxes. To select checkboxes with name="2" you should use

document.QuerySelector('[name="2"]:checked')

 function validateCheckboxes() { if (document.querySelector('[name="2"]:checked')) { alert('something is checked'); return true; } else { alert('NOTHING is checked'); return false; } }; 
 <form onsubmit="return validateCheckboxes();"> <h4>Which things do you enjoy?</h4> <input type='checkbox' name='2' value='12' id='2_12'> <label for='2_12'>&nbsp;&nbsp;Breathing</label><br /> <input type='checkbox' name='2' value='13' id='2_13'> <label for='2_13'>&nbsp;&nbsp;Watching paint dry</label><br /> <input type='checkbox' name='2' value='14' id='2_14'> <label for='2_14'>&nbsp;&nbsp;Nothing</label><br /> <br /> <br /> <input type="submit" value="Submit"> </form> 

With .2:checked you are testing against the class whereas 2 is the name value. Add class=2 to your checkboxes.

you could iterate over each checkbox to see if it is checked on submission.

cool I just learnt something, I didn't realize you could use pseudo selectors with querySelectorAll. I still think this is a valid pattern though, if you want to compare the total checked with the total checkboxes to make it more dynamic. without another expensive querySelector attribute call.

 function validateCheckboxes( form ){ var checkboxes = slice( form.querySelectorAll('[type=checkbox]') ), ret = checkboxes.reduce( function( total, checkbox ){ if( checkbox.checked ){ ++total; } return total; }, 0 ); console.log( ret + ' of ' + checkboxes.length + ' checkboxes checked' ); return false; // to cancel submission for stack } function slice( arr, start ){ return Array.prototype.slice.call( arr, start || 0 ); } 
 <script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script> <form onsubmit="return validateCheckboxes(this);"> <h4>Which things do you enjoy?</h4> <input type='checkbox' name='2' value='12' id='2_12'> <label for='2_12'>&nbsp;&nbsp;Breathing</label><br /> <input type='checkbox' name='2' value='13' id='2_13'> <label for='2_13'>&nbsp;&nbsp;Watching paint dry</label><br /> <input type='checkbox' name='2' value='14' id='2_14'> <label for='2_14'>&nbsp;&nbsp;Nothing</label><br /> <br /> <br /> <input type="submit" value="Submit"> 

The form element needed a closing tag </form>

The button needs to be a submit <input type="submit"/>

In order to get a HTMLCollection, use:
var chkList = document.querySelectorAll('input[type="checkbox"]:checked');

Then use a simple conditional against the collection's length: if (chkList.length > 0)

http://plnkr.co/edit/PXiQCk0f7Qu3H5EYIgOF?p=preview

 function validateCheckboxes() { var chkList = document.querySelectorAll('input[type="checkbox"]:checked'); if (chkList.length > 0) { alert('something is checked'); return true; } else { alert('NOTHING is checked'); return false; } } 
 <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css"> <script src="script.js"></script> </head> <body> <form onsubmit="return validateCheckboxes();" action="http://examples.funwebdev.com/process.php" method="post"> <fieldset> <legend>Which things do you enjoy?</legend> <input type='checkbox' name='2' value='12' id='2_12'> <label for='2_12'>&nbsp;&nbsp;Breathing</label> <br /> <input type='checkbox' name='2' value='13' id='2_13'> <label for='2_13'>&nbsp;&nbsp;Watching paint dry</label> <br /> <input type='checkbox' name='2' value='14' id='2_14'> <label for='2_14'>&nbsp;&nbsp;Nothing</label> <br /> <br /> <br /> <input type="submit" value="Submit"> </fieldset> </form> </body> </html> 

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