我正在尝试使用所选单选按钮的值发出提醒,但无论我选择哪一个,我总是得到第一个...(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);
}
答案 0 :(得分:2)
id
在文档中必须是唯一的。
要查找组中所选单选按钮的值,请按名称获取该组...
var radios = document.getElementsByName('radio_name'); // or
var radios = document.forms.formId.elements.radio_name;
然后循环遍历它们,直到找到具有真checked
属性的那个。
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);
答案 1 :(得分:0)
有道理,因为您有两个input
个标识具有相同的ID saida