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
>Solution :
- add an eventListener to the form submit
- 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>