我认为这很简单,但我确实需要一些帮助。感谢任何帮助!
我正在尝试从两组单选按钮捕获输入。第一组有效,而第二组无效。
这是我的代码:
的HTML
<p>Please select one from each group.</p>
<form action="#">
<fieldset>
<input type="radio" name="type" value="classic">classic type<br>
<input type="radio" name="type" value="modern">modern type<br>
<br>
<input type="button" onclick="typeface()" value="Review type selection">
<br><br>
<input type="text" id="type" size="50">
</fieldset>
<fieldset>
<input type="radio" name="layout" value="layout1">layout1<br>
<input type="radio" name="layout" value="layout2">layout2<br>
<br>
<input type="button" onclick="layout()" value="Review layout selection">
<br><br>
<input type="text" id="layout" size="50">
</fieldset>
<input type="submit" value="Submit">
</form>
JS(
</body>
之前)function typeface(){
var type = document.forms[0].type;
var txt = "";
var i;
for (i=0;i<type.length;i++){
if (type[i].checked){
txt = txt + type[i].value + " ";
}
}
document.getElementById("type").value = "You selected: " + txt;
}
function layout(){
var layout = document.forms[0].layout;
var txt = "";
var i;
for (i=0;i<layout.length;i++){
if (layout[i].checked){
txt = txt + layout[i].value + " ";
}
}
document.getElementById("layout").value = "You selected: " + txt;
}
最佳答案
不通过确认用户的广播选择激怒用户,而是执行以下操作:
DEMO
的HTML
<form id="myForm" action="#">
<fieldset>
<input type="radio" name="type" value="classic">classic type<br>
<input type="radio" name="type" value="modern">modern type<br>
<br>
<input type="text" id="type" size="50">
</fieldset>
<fieldset>
<input type="radio" name="layout" value="layout1">layout1<br>
<input type="radio" name="layout" value="layout2">layout2<br>
<br>
<input type="text" id="layout" size="50">
</fieldset>
<input type="submit" value="Submit">
</form>
JS:
function getId(id){ return document.getElementById(id); }
function writeVal(){
getId(this.name).value = "You selected: "+this.value;
}
var radio = getId('myForm').querySelectorAll('input[type=radio]');
for(var i=0; i<radio.length; i++) radio[i].onchange = writeVal;
上面的内容将立即在收音机
change
中起作用,并在text
字段中显示所选的文本值。