Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making sure at least one checkbox is checked

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.

JS (wrong)

function valthis(){  if (document.FC.c1.checked) {    alert ("thank you for checking a checkbox")   } else  {    alert ("please check a checkbox")   } } 

HTML

<p>Please select at least one Checkbox</p> <br> <br> <form name = "FC"> <input type = "checkbox" name = "c1" value = "c1"/> C1  <br> <input type = "checkbox" name = "c1" value = "c2"/> C2 <br> <input type = "checkbox" name = "c1" value = "c3"/> C3 <br>  <input type = "checkbox" name = "c1" value = "c4"/> C4  <br> </form> <br> <br>  <input type = "button" value = "Edit and Report" onClick = "valthisform();"> 

So what I ended up doing in JS was this:

function valthisform(){  var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked   if (chkd == true){   } else {     alert ("please check a checkbox")  }  } 

I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.

like image 314
MegaSly Avatar asked Aug 03 '12 00:08

MegaSly


People also ask

How do you check atleast one checkbox is checked?

$('#frmTest'). submit(function(){ if(! $('#frmTest input[type="checkbox"]').is(':checked')){ alert("Please check at least one."); return false; } }); is(':checked') will return true if at least one or more of the checkboxes are checked.

How do I allow only one checkbox to be checked?

change(function() { $("#myform input:checkbox"). attr("checked", false); $(this). attr("checked", true); }); This should work for any number of checkboxes in the form.


1 Answers

You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?

Here's a non-jQuery solution to check if any checkboxes on the page are checked.

var checkboxes = document.querySelectorAll('input[type="checkbox"]'); var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked); 

You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.

like image 57
mash Avatar answered Oct 08 '22 16:10

mash