问题描述
我有一个使用 JavaScript 构建 POST 语句的简单 Web 表单.在 Chrome 中,我可以使用简单的一行代码...
I have a simple web form that uses JavaScript for building a POST statement. In Chrome, I can use a simple line of code...
var form = document.forms['myForm'];
var env = form.env.value;
表单本身看起来像这样......
The form itself looks like this...
<form name="myForm" action='JavaScript:xmlhttpPost("/path/to/some/pythoncode.py")'>
<input type="radio" name="env" id="env" value="inside">Inside
<input type="radio" name="env" id="env" value="outside" checked="checked">Outside
<input type="radio" name="env" id="env" value="both">Both
<input type="radio" name="env" id="env" value="neither">Neither
我在表单上有一些文本框,我可以使用相同的技术来查找值(var name = form.fname.value
与<input type="text" name="fname" id="fname">
但是,当我提交表单并构建帖子时,单选按钮的值始终未定义.它在 Chrome 中运行良好,但在 IE 或 FireFox 中没有.
I have some text boxes on the form that I can use the same technique to find the value (
var name = form.fname.value
with a
<input type="text" name="fname" id="fname">
However, when I submit the form and build my post, the value for the radio buttons is always undefined. It works fine in Chrome, but nothing in IE or FireFox.
我尝试了 var env = document.getElementById('env').value
,但由于某种原因,无论我选择什么,它总是默认为第一个值(内部).该方法在使用 Chrome 时也不会返回值.
I tried var env = document.getElementById('env').value
, but for some reason that always defaults to the first value (inside) no matter what I select. That method also does not return a value when using Chrome.
在读取 FF 或 IE 中的无线电输入的检查值时,我是否缺少某些东西?
Is there something I'm missing for reading the checked value of a radio input in FF or IE?
推荐答案
试试这个
function getValueFromRadioButton(name) {
//Get all elements with the name
var buttons = document.getElementsByName(name);
for(var i = 0; i < buttons.length; i++) {
//Check if button is checked
var button = buttons[i];
if(button.checked) {
//Return value
return button.value;
}
}
//No radio button is selected.
return null;
}
ID 是唯一的,因此您不应为多个项目使用相同的 ID.如果您使用此功能,您可以删除所有单选按钮 ID.
IDs are unique so you should not use the same ID for multiple items. You can remove the all the radio button IDs if you use this function.
这篇关于JavaScript 读取 IE 和 FireFox 中的单选按钮值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!