-2

I want to limit the selection of checkboxes through limit_checkbox() function but when i declare the name of input to an array it is not responding. The error shows " Uncaught ReferenceError: limit_checkbox is not defined at HTMLInputElement.onclick"

<div class="form-group w-25" id="ch1">
  <input type="checkbox" value="delta" name="band[]" onclick="limit_checkbox(2,this)">
  <label>Delta</label>
</div>
<div class="form-group w-25">
  <input type="checkbox" value="theta" name="band[]" onclick="limit_checkbox(2,this)">
  <label>Theta</label>
</div>
<div class="form-group w-25">
        <input type="checkbox" value="alpha" name="band[]" onclick="limit_checkbox(2,this)">
        <label>Alpha</label>
      </div>
<script>
  var a, b = false;

  function limit_checkbox(max, obj) {
    var x = document.getElementsByName("band");
    var count = 0;
    for (var i = 0; i < x.length; i++) {
      if (x[i].checked) {
        count += 1;
      }
    }
    if (count > max) {
      alert('You can select only ' + max + ' checkboxes.');
      obj.checked = false;
    }
  }
</script>
Beren
  • 684
  • 2
  • 9
  • 14
  • The name _isn’t_ `band` any more now, so of course you need to modify `document.getElementsByName("band")` accordingly … – CBroe May 18 '20 at 12:08
  • The code in your question does not produce the error you describe. It seems like you did not post your code verbatim. If the inline handler can't see `limit_checkbox`, then `limit_checkbox` is not declared on the top level. Better to avoid inline handlers entirely - see https://stackoverflow.com/a/59539045 – CertainPerformance May 18 '20 at 12:09

1 Answers1

0

Add[] in band i.e : document.getElementsByName("band[]") because javascript is not able to find that inputs .

Working Code :

var a, b = false;

function limit_checkbox(max, obj) {
  //getting element by name
  var x = document.getElementsByName("band[]");
  var count = 0;
  for (var i = 0; i < x.length; i++) {
    if (x[i].checked) {
      //incrementing
      count++;
    }
  }
  if (count > max) {
    alert('You can select only ' + max + ' checkboxes.');
    obj.checked = false;
  }
}
<div class="form-group w-25" id="ch1">
  <input type="checkbox" value="delta" name="band[]" onclick="limit_checkbox(2,this)">
  <label>Delta</label>
</div>
<div class="form-group w-25">
  <input type="checkbox" value="theta" name="band[]" onclick="limit_checkbox(2,this)">
  <label>Theta</label>
</div>
<div class="form-group w-25">
  <input type="checkbox" value="alpha" name="band[]" onclick="limit_checkbox(2,this)">
  <label>Alpha</label>
</div>
Swati
  • 28,069
  • 4
  • 21
  • 41