Home > front end >  printing multiple checkbox results into binary string
printing multiple checkbox results into binary string

Time:10-03

I have multiple checkboxes (for the months of the year) on a HTML page and want to pick up the users option into a binary string (ex. 011001110101) and print it out on the same page.

So, far I can print out the first month but I'm unable to add the rest to the string. Can you help me out?

function RegMD() {
    var checkBox = document.getElementById("jan");
    var text = document.getElementById("text");
    var text1 = 1;
    var text2 = 0;
    if (checkBox.checked == true){
     document.getElementById("text").innerHTML = text1;
  } else {
     document.getElementById("text").innerHTML = text2;
  }
}
<input type="checkbox" id="jan"><label>january</label><br>
<input type="checkbox" id="feb"><label>february</label><br>
<input type="checkbox" id="mar"><label>march</label><br>
...

<br>
<p id="text"></p>
<br>
<button type="button" onclick="RegMD()">Register My Data</button>

CodePudding user response:

You can use document.querySelectorAll to get all the checkboxes, then Array#reduce to construct the binary string.

const checkboxes = [...document.querySelectorAll('input[type=checkbox]')];
function RegMD() {
    document.getElementById("text").textContent =
      checkboxes.reduce((a, b) => a   (b.checked ? 1 : 0), "");
}
<input type="checkbox" id="jan"><label>january</label><br>
<input type="checkbox" id="feb"><label>february</label><br>
<input type="checkbox" id="mar"><label>march</label><br>
...

<br>
<p id="text"></p>
<br>
<button type="button" onclick="RegMD()">Register My Data</button>

CodePudding user response:

const checkboxes = [...document.querySelectorAll('input[type=checkbox]')];
function RegMD() {
  let str="";
    checkboxes.forEach((res)=>{
     str =res.checked===true?'1':'0';
    })
    document.getElementById("text").innerHTML = str;
}
  • Related