0

我正在尝试使用所选单选按钮的值发出警报,但我总是得到第一个,无论我选择哪个......(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);
           }

任何的想法 ?


@Quentin:我有很多警报,因为我试图从表单中获取所有数据。我使用了您的代码,但根本没有收到任何警报。

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);

}
4

2 回答 2

2

一个id在文档中必须是唯一的。

要查找组中选定单选按钮的值,请按组名获取组...</p>

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

然后遍历它们,直到找到具有 truechecked属性的那个。

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);
于 2012-11-12T16:58:23.043 回答
0

有道理,因为您有两个input具有相同 id 的标签saida

于 2012-11-12T16:56:48.967 回答