0

i have a simple form like this :

<form id="formSearch">
<label><input type="radio" name="number" value="1">singular</label><br>
<label><input type="radio" name="number" value="2">plural</label><br><br>
<INPUT type="Submit" Value="Show" name="show" ></INPUT>
</form>

I want to get the "radio-value" of the selected button with javascript :

var account = document.getElementsByName("number").value;

do not give the correct response. if I give a trap :

alert(account);

the result is : undefined. I do not know where the harm, is there who is willing to help me, thanks

agus priyo
  • 95
  • 1
  • 9

3 Answers3

1

Using javascript:

document.querySelector('[name=number]:checked').value;
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

In jquery, you can use the checked attribute selector for that

$("[name='number']:checked").val()
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
0

function test() {
  
  var checkedRadioBtnList=new Array();
  
  var account = document.getElementsByName("number");
  
  for(i=0; i<account.length;i++){  
    if(account[i].checked){      
      checkedRadioBtnList.push({value:account[i].value});
    }    
  }
  
  console.log(checkedRadioBtnList);
}
<form id="formSearch">
<label><input type="radio" name="number" value="1">singular</label><br>
<label><input type="radio" name="number" value="2">plural</label><br><br>
<INPUT type="Submit" Value="Show" name="show" onclick="test()" ></INPUT>
</form>

getElementsByName will return an array.

EDIT

I had simply answer the question, how to get checked value using javascript.

There are lots of option to store values as per application. I have improve my answer to store checked radio button values in an Array using JSON Object.

Jitendra Tiwari
  • 1,651
  • 3
  • 14
  • 28