Search code examples
javascripthtmlforms

How to iterate named checkbox that either returns a input element or a RadioNodeList?


A search result can have from zero to many items. The search result/ the items are presented in a list with a checkbox for each item. All the checkboxes have the same name ("countrycode") and different values/IDs.

To get a named element I can use e.target.countrycode where the target is the form. Now, I would like to iterate all the checkboxes and make them checked, but the issue is that when there is only one search result e.target.countrycode returns the input element and when there are more e.target.countrycode returns a RadioNodeList.

What would be a good approach when I don't know if there is one or more items?

document.addEventListener('submit', e => {
  e.preventDefault();
  for(const input of e.target.countrycode){
    input.checked = true;
  }
});
form {
  display: flex;
  flex-direction: column;
  margin-bottom: 1em;
}
<form name="form01">
  <label><input type="checkbox" value="1" name="countrycode">Item 1</label>
  <label><input type="checkbox" value="2" name="countrycode">Item 2</label>
  <label><input type="checkbox" value="3" name="countrycode">Item 3</label>
  <label><button type="submit">Check all</button></label>
</form>

<form name="form02">
  <label><input type="checkbox" value="1" name="countrycode">Item 1</label>
  <label><button type="submit">Check all</button></label>
</form>


Solution

  • If e.target.countrycode has a length property it must be a RadioNodeList, otherwise the single element can be inserted into an array. In both cases the inputs is then iterable and can be used in the for loop.

    document.addEventListener('submit', e => {
      e.preventDefault();
      let countrycode = e.target.countrycode;
      if (countrycode) {
        // if it has length then is must be a radionodelist
        let inputs = (countrycode.length) ? countrycode : [countrycode];
        for (const input of inputs) {
          input.checked = true;
        }
      }
    });
    form {
      display: flex;
      flex-direction: column;
      margin-bottom: 1em;
    }
    <form name="form01">
      <label><input type="checkbox" value="1" name="countrycode">Item 1</label>
      <label><input type="checkbox" value="2" name="countrycode">Item 2</label>
      <label><input type="checkbox" value="3" name="countrycode">Item 3</label>
      <label><button type="submit">Check all</button></label>
    </form>
    
    <form name="form02">
      <label><input type="checkbox" value="1" name="countrycode">Item 1</label>
      <label><button type="submit">Check all</button></label>
    </form>