Javascript getElementById() 适用于文本框,但不适用于单选按钮或下拉选择器

标签 javascript html

好吧,在折腾了很多天并阅读了无数帮助页面之后,是时候寻求帮助了。这段代码没有问题。我在表单中输入的任何文本都会显示在弹出框中。很好。

<script>
function yesorno1(){
	var form = document.getElementById('escalation');
	if(form.value != "")
		alert("You entered: " + form.value)
	else
		alert("There is some problem")		
}
</script>
<input type='text' id='escalation' />
<input type='button' onclick='yesorno1()' value='Submit' />

如果我将 HTML 从表单更改为单选按钮或下拉选择器,弹出框将始终仅显示列表中第一个单选或第一个下拉选项的值。例如,在下面的代码中,第一个单选选项是“yes”,第二个单选选项是“no”。无论我选择"is"还是“否”,弹出框总是给出"is"。

<script>
function yesorno2(){
	var rad = document.getElementById('escalation2');
	if(rad.value != "")
		alert("You entered: " + rad.value)
	else
		alert("There is some problem")		
}
</script>

Is this an escalation?<br>
<input type='radio' id='escalation2' value='yes'> Yes<br>
<input type='radio' id='escalation2' value='no'> No<br><br>
<input type='button' onclick='yesorno2()' value='Submit' />

有谁知道一种编码方法,以便单选 yes 会给出弹出消息"is",而单选 no 会给出弹出消息 no?

最佳答案

<script>
function yesorno2(){
	var rad = document.getElementById('theForm').elements['escalation2'];
	if(rad.value != "")
		alert("You entered: " + rad.value)
	else
		alert("There is some problem")		
}
</script>
<form id='theForm'>
Is this an escalation?<br>
<input type='radio' name='escalation2' value='yes'> Yes<br>
<input type='radio' name='escalation2' value='no'> No<br><br>
<input type='button' onclick='yesorno2()' value='Submit'>
</form>

你犯了两个错误:

  • 单选按钮的通用属性是name,而不是id
  • 不要“捕获”单选按钮,而是选择表单元素:它包含一个数组(elements),使您可以“作为一个组”直接访问单选按钮。您可以在其中找到

注意:如果使用 Firefox,您需要版本 33(2014-10-14 发布)或更高版本。 RadioNodeList 终于到达了 Firefox。

关于Javascript getElementById() 适用于文本框,但不适用于单选按钮或下拉选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26706269/

相关文章:

html - 如何占用div之间的中心空间?

javascript - 如何在一个高度大的div周围 float 高度小的div

javascript - 模块导出中的 NodeJS 多个函数

javascript - 向数组中的特定对象添加属性

javascript - JavaScript从HTML block 元素中删除了双括号(带有内部文本)

java - 从 URL 检索 HTML 标签和纯文本

java - 如何使用 Java 将单个 HTML 拆分为多个 HTML 文件

javascript - 为什么会出现 Uncaught TypeError : Cannot read property 'dataSource' of undefined

javascript - ReactJS - .setState 成功调用后其他属性变得未定义

javascript - 如何使用 JQuery 和 Javascript 为响应式图像 slider 设置图像宽度