views:

74

answers:

2

i have 3 elemests of radio group. How can i get the value of the radio element?

can i have same id for all 3 elements?

??<input type="radio" id="ans" name="ans" value="1" /> <input type="radio" id="ans" name="ans" value="0" />

how will i get the value of ans

A: 

I do not recommend having the same id for all 3 elements. You do have to have the same name for each button in order for it to be part of the group. If you have the form its in, you can do this

var myForm = document.getElementById('myForm');
var radioVal = myForm.ans.value;

That will give you your value.

Zoidberg
+1  A: 

Id's must be unique, you should have the radio buttons with the same name, and get its value iterating through them:

<input type="radio" name="ans" value="1" />
<input type="radio" name="ans" value="0" />


var elements = document.getElementsByName('ans'), //or document.forms['name'].ans
    i, el;

for (i = 0; i < elements.length;i++) {
  el = elements[i];
  if (el.checked) {
    alert(el.value);
    break;
  }
}

getElementsByName('ans'), or document.forms['name'].ans returns an array object, containing the elements with the name ans.

CMS