Pick up value from a radio button

Asked

Viewed 13,847 times

0

How would I get the values of the radio button? I tried with the code below, but only returns me the value of the first:

<input type='radio' name='Seguro' id="seguro" onchange="soma()" value='Sim'> Sim
<input type='radio' name='Seguro' id"seguro" onchange="soma()" value='Não'> Não

And the javascript ( test ):

function soma(){

....
alert(document.getElementById("seguro").value);
....

}
  • 1

    take a look at this, maybe it won’t help you&#xD; http://stackoverflow.com/questions/604167/how-can-we-access-the-value-of-a-radio-button-using-the-dom

3 answers

1


You can use this solution that is in Stackoverflow english.

var choices = [];
var els = document.getElementsByName('choice_shrd_with_me');
for (var i=0;i<els.length;i++){
  if ( els[i].checked ) {
    choices.push(els[i].value);
  }
}

0

In your case the two inputs are with the same id, you can change the id, or pass the element itself as a function parameter like this = onchange="soma(this)"; and then change your js to receive the parameter.

-1

Hello

try instead of:

alert(document.getElementById("seguro").value);

utilise:

var seg = document.querySelector('input[name=seguro]:checked').value
alert(seg)

or even:

alert(document.querySelector('input[name=seguro]:checked').value)

I hope to help someone, even after so long, because I myself was helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.