Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use radio button where each button is dedicated to one array value?

So what I am trying to do is create a radio button of, say 5 options. Because it’s a radio button, obviously only one option can be selected. I want this array button to insert five values to an array where the selected gives the value of 1, and the others 0.

Let’s say I have five options: A, B, C, D, E

<form method="POST">
  <input type="radio" id="html" name="fav_language" value="1">A<br>
  <input type="radio" id="html" name="fav_language" value="1">B<br>
  <input type="radio" id="html" name="fav_language" value="1">C<br>
  <input type="radio" id="html" name="fav_language" value="1">D<br>
  <input type="radio" id="html" name="fav_language" value="1">E<br>
<button type="submit" value="Submit">Submit</button>
</form>

If select option B, how can I put it in an array so that it equals [0,1,0,0,0].
Is there a simple way to do this?
Thank you so much

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  1. add an eventListener to the form submit
  2. cast a querySelectorAll to array and map the truthyness of the checked attribute
document.getElementById("myForm").addEventListener("submit", function(e) {
  e.preventDefault(); // remove if you want the form to submit
  const arr = [...document.querySelectorAll("[name=fav_language]")]
    .map(rad => +rad.checked);
  console.log(arr)
})
<form method="POST" id="myForm">
  <input type="radio" id="html" name="fav_language" value="1">A<br>
  <input type="radio" id="html" name="fav_language" value="1">B<br>
  <input type="radio" id="html" name="fav_language" value="1">C<br>
  <input type="radio" id="html" name="fav_language" value="1">D<br>
  <input type="radio" id="html" name="fav_language" value="1">E<br>
  <button type="submit" value="Submit">Submit</button>
</form>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading