在同一HTML页面中使用Javascript获取单选按钮的值
我是javascript编码新手 我正在自己创建一个调查页面。我会以“真或假”的形式提问,以1分的形式回答为真,以0分的形式回答为假。将会有多个问题 我试图通过getElementsByName来实现,但没有成功。我的代码是这样的。有人能帮我吗在同一HTML页面中使用Javascript获取单选按钮的值,javascript,Javascript,我是javascript编码新手 我正在自己创建一个调查页面。我会以“真或假”的形式提问,以1分的形式回答为真,以0分的形式回答为假。将会有多个问题 我试图通过getElementsByName来实现,但没有成功。我的代码是这样的。有人能帮我吗 <form> <input type="radio" name="question1" value="1" id="q1"> true <input type="radio" name="question1" value="
<form>
<input type="radio" name="question1" value="1" id="q1"> true
<input type="radio" name="question1" value="0" id="q1"> false
</form>
<button onclick="myFunction()">try</button>
<script>
function myFunction()
{
var x=document.getElementsByName("question1").value;
window.alert("your score is " +x);
}
</script>
真的
假的
尝试
函数myFunction()
{
var x=document.getElementsByName(“问题1”).value;
window.alert(“您的分数为”+x);
}
按名称分组的单选按钮与选择
元素的行为不同,即该组没有单个值。另外getElementsByName()
返回一个类似数组的对象(参见Felix Kling的注释)
我建议您这样做(在向表单
提供id之后):
函数myFunction(){
var form=document.getElementById('form'),//对表单元素的引用
question=form['question1'],//从具有属性name=“question1”的元素创建HTMLCollection
n、 //循环索引
对于(n=0;n
问题
定义中的括号符号用于将来的用途。如果您有更多的单选按钮组,这些单选按钮组可以使用相同的函数处理,您可以将组的名称传递给函数,然后在括号中使用该参数而不是文字值('question1'
)。提示:getElement s ByName。该方法返回一组元素。请查看文档:。同一页面中的两个或多个元素可以共享一个ID。更改第二个收音机id。。如何获取“问题1”的值?当我使用“getElementById”时,它以任何方式显示“1”。您需要更改单选按钮的ID
。ID
必须是唯一的。把q1
和q2
作为ID
好的,我知道了。我把id改为q1和q2。但是现在如何使用单选按钮将“x”变量定义为1或0呢?
function myFunction () {
var form = document.getElementById('form'), // a reference to the form element
question = form['question1'], // creates a HTMLCollection from elements having attribute name="question1"
n; // loop index
for (n = 0; n < question.length; n++) { // iterates through items in HTMLCollection
if (question[n].checked) { // checks the current item's 'checked' property
alert("your score is " + question[n].value); // found the checked-one
break; // "checked" found, no need to search more
}
}
}