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

Time:12-15

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

CodePudding user response:

  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>

CodePudding user response:

Added an onSubmit function to the form which gets executed when the button is pressed. The function then assigns the values in the array according to the option selected by the user.

let arr = [];
const createArray = (e) => {
  radios = document.getElementsByName("fav_language");
  for (var i = 0, length = radios.length; i < length; i  ) {
    arr[i] =  radios[i].checked;
  }
  console.log(arr);
}
<form method="POST" onsubmit="createArray()">
  <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>

  • Related