aaron lilly
aaron lilly

Reputation: 274

Javascript Validation for Multichoice Checkboxes

I would like to create an alert that displays if none of the choices in my check box have been displayed.

<script>

function mFunction () {
  if (!!this.form.checkbox.checked) {
    alert('not checked');
    return false;
  }
};
</script>

js above

<body>

<form>
  <input type="checkbox" name="choice1" value="choice1" id="confirm">choice 1<br>
  <input type="checkbox" name="choice2" value="choice2" >choice 2<br>
  <input type="checkbox" name="choice3" value="choice3">choice 3<br><br>
  <input type="submit" value="Submit" onclick="mFunction()"> 
</form>

I wanted an alert if nothing selected, and no alert if something is selected.

Upvotes: 1

Views: 172

Answers (3)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92347

you can check this by

[...document.querySelectorAll("input[type='checkbox']")].some(i=>i.checked)

function mFunction (e) 
{  
  if(![...document.querySelectorAll("input[type='checkbox']")].some(i=>i.checked))
  {
     alert('not checked');
     e.preventDefault();
  }
};

function checkForm(t,e) { 
  e.preventDefault();
  console.log('checked'); 
};
<form onsubmit="checkForm(this,event);">
  <input type="checkbox" name="choice1" value="choice1" id="confirm">choice 1<br>
  <input type="checkbox" name="choice2" value="choice2" >choice 2<br>
  <input type="checkbox" name="choice3" value="choice3">choice 3<br><br>
  <input type="submit" value="Submit" onclick="mFunction(event)"> 
</form>

Upvotes: 1

Atul
Atul

Reputation: 3423

You can directly check the checked items like below.

   function mFunction () {
    let matches = document.querySelectorAll('input[type=checkbox]:checked');
    if (matches.length < 1) {
        alert('not checked');
        return false;
    }
   };

Upvotes: 1

Rk R Bairi
Rk R Bairi

Reputation: 1359

If its plain javascript, you can try adding an event listener when checkbox is clicked.

Maintain an array in the listener. If something is selected maintain a checkbox selection counter or boolean tracking selection.

 var checkbox = document.querySelector("input[name=checkbox]");

checkbox.addEventListener( 'change', function() {
 if(this.checked) {
    // Checkbox is checked..
 } else {
    // Checkbox is not checked..
 }
});

Upvotes: 0

Related Questions