How to get the values of all radio button as array ? | SoloLearn: Learn to code for FREE!

+2

How to get the values of all radio button as array ?

function afterButtonClick() { var values = []; for( j = 1; j < 25; j++ ) {      var ele = document.getElementsByName('radio'+j);                      for(i = 0; i < 2; i++) {                  if(ele[i].checked) {                 var result  = ele[i].value;              }      values.push(result);  }     }       alert(values); } Output values= yes,yes,No,yes,no like this

5/28/2020 1:26:58 PM

Prince Chaurasia

9 Answers

New Answer

+3

You can use the for/of loop to iterate over the HTML collection of radio buttons. This way you don't need to worry about the length or index of the collection. And within the loop push the element value, if it is checked, to the array. https://code.sololearn.com/WoUrFl5expSO/#html

+2

Prince Chaurasia It will be helpful if you save your code in code playground & link it here

+1

Assign all your radio buttons to one class: HTML: <input type="radio" class="r"/> Do this for all radio inputs you wanna get. Then js: JS: var arr = document.getElementsByClassName("r"); arr is now an array of all your selected inputs.

+1

𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 https://code.sololearn.com/Wyt54tX400cN/?ref=app

+1

Deep_Blue https://code.sololearn.com/Wyt54tX400cN/?ref=app

+1

Deep_Blue Show only 1st value

+1

Want to get all button value after submit

+1

The problem was: var result always got redifined in the loop and values only got pushed by the last value. So I decided to push values directly in the loop.

-1

You have to call js in window.onload so that the html is loaded. There you go: https://code.sololearn.com/WFKv5DMxTJ1h/?ref=app