Martín Blanco Landa Martín Blanco Landa - 2 months ago 8
HTML Question

Form: "Select all" button with multiple-choice checkboxes

I'm trying to make the "Select all" and "Remove all" buttons work in my form but i'm having lots of trouble. In fact, if I remove the "[]" (array) to the name attribute of the checkboxes, that javascript code totally works. But I need these checkboxes to be multiple-choice so that code isn't working.

I leave here the HTML and JS code related to the checkboxes, but I recommend you to check this JS Fiddle, so you can check it more graphically:

https://jsfiddle.net/28dsnmxs/

HTML Code:

<input type="checkbox" name="h[]" value="1" id="g"> SMS
<br/>
<input type="checkbox" name="h[]" value="2" id="g"> E-mail
<br/>
<input type="checkbox" name="h[]" value="3" id="g"> Phone
<br/>
<input type="button" id="prueba" name="sub" value="Check all" onclick="checkall(document.formulario.h)">
<input type="button" name="sub" value="Uncheck all" onclick="uncheckall(document.formulario.h)">


JS Code:

function checkall(chk) {

var i;
for (i = 0; i < chk.length; i++) {
chk[i].checked = true;
}

}
function uncheckall(chk) {
var i;
for (i = 0; i < chk.length; i++) {
chk[i].checked = false;
}
}


How can I make it work? Ideas avoiding jQuery are preferred, but no problem if there is no other way. Thank you!

Answer

To access key of object which is not a valid JavaScript Identifier, use bracket-notation

Use document.formulario['h[]'] to select all name = "h[]" elements

function checkall(chk) {
  var i;
  for (i = 0; i < chk.length; i++) {
    chk[i].checked = true;
  }

}

function uncheckall(chk) {
  var i;
  for (i = 0; i < chk.length; i++) {
    chk[i].checked = false;
  }
}
<form method="POST" action="" name="formulario" id="form">
  <input type="checkbox" name="h[]" value="1" id="g">SMS
  <br/>
  <input type="checkbox" name="h[]" value="2" id="g">E-mail
  <br/>
  <input type="checkbox" name="h[]" value="3" id="g">Phone
  <br/>
  <input type="button" id="prueba" name="sub" value="Check all" onclick="checkall(document.formulario['h[]'])">
  <input type="button" name="sub" value="Uncheck all" onclick="uncheckall(document.formulario['h[]'])">
</form>