Nelson Silva
Nelson Silva

Reputation: 439

getelementbyid issue with radio button

I'm trying to make an alert with the value of the selected radio button, but I allways get the first of them, regardless the one I choose...(Acompanhado);

html:

          <form/>

          <input type="radio" class="simple_form" name="grupo_1" value="Acompanhado" id="saida"/>
          <span class="texto">Acompanhado</span>
          <input type="radio" class="simple_form" name="grupo_1" value="Individual" id="saida"/>
          <span class="texto">Individual</span>
          </form>

js:

           function save() {
       var saida_js = document.getElementById('saida').value;
       alert("Tipo de saida: " + saida_js);
           }

Any idea ?


@Quentin: I have alot of alerts, cause Im trying to get all data from a form. I used your code, and I get no alert at all.

function save() {
    var morada_js = document.getElementById('morada').value;
    var data_js = document.getElementById('data').value;
    var hora_js = document.getElementById('hora').value;

    var radio_saida = document.getElementsByName('name_saida');

    var notas_js = document.getElementById('notas').value;
        var condicoes_atm_js = document.getElementById('condicoes_atm').value;


    alert("Morada: " + morada_js);
    alert("Data: " + data_js);
    alert("Hora: " + hora_js);

        function get_checked_radio(radio_saida) {
        for (var i = 0; i < radio_saida.length; i++) {
            var current = radio_saida[i];
            if (current.checked) {
                return current;
                }
            }
        }

    alert(get_checked_radio(radio_saida).value);
    alert("Notas: " + notas_js);

}

Upvotes: 0

Views: 3218

Answers (2)

Quentin
Quentin

Reputation: 943649

An id must be unique in a document.

To find the value of a selected radio button in a group, get the group by its name…

var radios = document.getElementsByName('radio_name'); // or
var radios = document.forms.formId.elements.radio_name;

Then loop over them until you find the one with the true checked property.

function get_checked_radio(radios) {
    for (var i = 0; i < radios.length; i++) {
        var current = radios[i];
        if (current.checked) {
            return current;
        }
    }
}

alert(get_checked_radio(radios).value);

Upvotes: 2

user1796666
user1796666

Reputation:

Makes sense because you've got two input tags with the same id saida

Upvotes: 0

Related Questions