0

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/

fionaredmond
  • 571
  • 6
  • 15
Digital Fusion
  • 139
  • 1
  • 15
  • I'm, not sure if '2_12' is a valid id -edit-, oh, in HTML 5 it is. – GolezTrol Dec 30 '15 at 20:12
  • 3
    your button is not a submit button. Clicking on it will do nothing – Bindrid Dec 30 '15 at 20:15
  • 1
    You need to replace your query for an element with one that targets the ones you're interested in. The following works with your html as is (no need to add classes to the inputs. `document.querySelectorAll('input[type=checkbox]:checked')` - **EDIT:** Though you still need to make the `validateCheckboxes` function fire, as Bindrind says. – enhzflep Dec 30 '15 at 20:17
  • Sorry, This is a stripped down version of my actual code, I missed the submit button issue. – Digital Fusion Dec 30 '15 at 20:28
  • If I use document.querySelectorAll('input[type=checkbox]:checked'), then I will have issues when there are multple questions that have checkboxes? not all questions will be required – Digital Fusion Dec 30 '15 at 20:29
  • @DigitalFusion - yes. See Barmar's answer. – enhzflep Dec 30 '15 at 20:40

4 Answers4

1

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>
Barmar
  • 596,455
  • 48
  • 393
  • 495
0

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

Fabrizio Mazzoni
  • 1,583
  • 1
  • 18
  • 38
  • 1
    See also [which characters are valid in CSS class names selectors](http://stackoverflow.com/questions/448981/which-characters-are-valid-in-css-class-names-selectors). – GolezTrol Dec 30 '15 at 20:14
  • I tried that (fiddle updated: https://jsfiddle.net/r6c4hxhj/11/). Im still getting some issue that completely breaks fiddles processing – Digital Fusion Dec 30 '15 at 20:34
  • Check the Javascript console. There's an error message saying that `.2:checked` is not a valid selector. – Barmar Dec 30 '15 at 20:42
  • Try using a class that isn't a number. – Barmar Dec 30 '15 at 20:42
0

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">
synthet1c
  • 5,543
  • 2
  • 15
  • 30
0

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>
zer00ne
  • 31,838
  • 5
  • 32
  • 53