我有一个表格,有文字,下拉和单选按钮。我有一个脚本,然后抓取这些值并在文本区域字段中显示这些值。我可以获取文本的值,但单选按钮总是返回一个未定义的错误或对象节点列表错误。下面是我在表单标记中所做工作的示例代码:
<form>
<input type="text" id="name" onChange="mySummary();" />
<input type="text" id="phone" onChange="mySummary();" />
<input type="radio" name="contact" value="Spoke with" onChange="mySummary();" />
<input type="radio" name="contact" value="left voicemail" onChange="mySummary();" />
<input type="text" id="moreinfo" onChange="mySummary();" />
<textarea id="Summary" rows="10" cols="30"></textarea>
</form>
然后,我按如下方式调用JavaScript中的数据:
function mySummary() {
var a = document.getElementById("name").value;
var b = document.getElementById("phone").value;
var c = document.getElementsByName("contact").value;
var d = document.getElementById("moreinfo").value;
document.getElementById("Summary").innerHTML =
"Name: " + a + "\n" +
"Phone: " + b + "\n" +
"Contacted How: " + c + "\n" +
"Additional information" + d;
}
当我尝试使用上面的信息时,我会得到未定义的消息--请注意无线电选项。
如何提取为单选按钮选择的内容的值,以及用户将值更改到新的选择时,输出也会发生变化。我已经搜索过,但还没有找到在innerHTML中与其他in一起使用的
发布于 2018-03-17 08:19:54
您可以使用名称contact
遍历单选按钮组中的所有单选按钮,并检查选中哪个单选按钮。然后,在变量c
中设置该单选按钮的值。
function mySummary() {
var a = document.getElementById("name").value;
var b = document.getElementById("phone").value;
var radioBtn = document.getElementsByName("contact");
var c;
for(i=0; i<radioBtn.length; i++){
if(radioBtn[i].checked){
c = radioBtn[i].value;
}
}
var d = document.getElementById("moreinfo").value;
document.getElementById("Summary").innerHTML =
"Name: " + a + "\n" +
"Phone: " + b + "\n" +
"Contacted How: " + c + "\n" +
"Additional information" + d;
}
<form>
<input type="text" id="name" onChange="mySummary();" />
<input type="text" id="phone" onChange="mySummary();" />
<input type="radio" name="contact" value="Spoke with" onChange="mySummary();" />
<input type="radio" name="contact" value="left voicemail" onChange="mySummary();" />
<input type="text" id="moreinfo" onChange="mySummary();" />
<textarea id="Summary" rows="10" cols="30"></textarea>
</form>
发布于 2018-03-17 08:27:50
顾名思义,它以数组的形式返回多个项,因此代码中'c‘的值将是一个数组,但是,由于单选按钮通常用于在两个选项之间进行选择,而且在单选按钮上也只有两个选项,您也可以为单个单选按钮获得id,并通过使用getElementById并检查其“选中”属性来获得对它的引用,以确定是否选中了单选按钮,或者您也可以循环。
https://stackoverflow.com/questions/49333821
复制相似问题