Home > Blockchain >  How to check specific number of checbox and disable remaining using javscript?
How to check specific number of checbox and disable remaining using javscript?

Time:03-02

How to check specific number of checbox and disable remaining using javscript?

  <div >
      <input type="checkbox" />1 
      <input type="checkbox" />2 
      <input type="checkbox" />3<br/>
      <input type="checkbox" />4 
      <input type="checkbox" />5 
      <input type="checkbox" />6<br/>
      <input type="checkbox" />7 
      <input type="checkbox" />8 
      <input type="checkbox" />9<br/>
      <input type="checkbox" />10 
      <input type="checkbox" />11 
      <input type="checkbox" />12<br/>
      <input type="checkbox" />13 
      <input type="checkbox" />14 
      <input type="checkbox" />15
    </div>

enter code here

CodePudding user response:

<input id='1' type='checkbox' value='1'/>

in javascript:

let value = document.getElementById('1').value;

CodePudding user response:

Change the <div> into a <form> so you can take advantage of the HTMLFormElement interface. In the example there are no checks for parameter, which you can do yourself (ex. if a string is passed or if the number is greater than the number of checkboxes).

Details are commented in example below.

// param must be a Number
function checkN(num) {
  // Reference the <form>
  const form = document.forms.vipGuests;
  /* Collect all <input>s in <form> and turn 
     Collection into an Array 
  */
  const checkboxes = [...form.elements];
  /* Iterate through Array...
     check all checkboxes until the given number is 
     reached, then disable the rest
  */
  for (let c = 0; c < checkboxes.length; c  ) {
    if (c < num) {
      checkboxes[c].checked = true;
    } else {
      checkboxes[c].disabled = true;
    }
  }
};

checkN(7);
<!--Change <div> into a <form> and class into id-->
<form id="vipGuests">
  <input type="checkbox" />1
  <input type="checkbox" />2
  <input type="checkbox" />3<br/>
  <input type="checkbox" />4
  <input type="checkbox" />5
  <input type="checkbox" />6<br/>
  <input type="checkbox" />7
  <input type="checkbox" />8
  <input type="checkbox" />9<br/>
  <input type="checkbox" />10
  <input type="checkbox" />11
  <input type="checkbox" />12<br/>
  <input type="checkbox" />13
  <input type="checkbox" />14
  <input type="checkbox" />15
</form>

  • Related