Is there a way to check the form before submitting it to check if any checkboxes are checked?

Is there a way to check the form before submitting it to see if ANY checkbox is checked in Javascript?

Sort of...

function checkboxcheck(){ /*something in here to check name="brands[]" checkbox array?*/ } 

Basically, I just want him to warn me if 0 flags are selected. 1 or more is required.

I would call this function in submit.

Thanks a lot!

+4
source share
2 answers

What about:

 function checkboxcheck(name) { var els = document.getElementsByName(name); for (var i = 0; i < els.length; i++) { if (els[i].checked) { return true; } } return false; } 

using getElementsByName() .

Using:

 var valid = checkboxcheck("brands[]"); 

Here is an example: http://jsfiddle.net/andrewwhitaker/2saJp/1/

0
source

You can do something like this:

 function anyCheckboxesChecked() { var inputs = document.getElementsByTagName('input'); for (var i = 0; i < inputs.length; ++i) { if (inputs[i].type === "checkbox" && inputs[i].checked) return true; } return false; } 

Then you can call this function from the submit handler

  if (!anyCheckboxesChecked()) { alert("Please check one of the appealing checkboxes on the page"); return false; } 

If your page is more complex than it means (for example, if there are several forms), you must first find the appropriate form and call .getElementsByTagName() from this point instead of document .

+3
source

Source: https://habr.com/ru/post/1337881/


All Articles