Mozilla Firefox中的未定义错误

时间:2014-11-01 06:52:03

标签: javascript html

为什么我在Firefox和IE中收到未定义的错误。此代码适用于Google Chrome。以下是完整代码http://liveweave.com/fUhpiI

这是我的HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="css/hpstyles.css" rel="stylesheet">
<script src="js/hpjs.js"></script>
</head>
<body>
<form id="hp">
    <div>
    <h2>1. Which one do you prefer?</h2>
    <div>   
        <input type="radio" name="q1" id="radio1" class="radio" value="9"/>
        <label for="radio1">Tea</label>
    </div>
    <div>   
        <input type="radio" name="q1" id="radio2" class="radio" value="4"/>
        <label for="radio2">Coffee</label>
    </div>
    <div>   
        <input type="radio" name="q1" id="radio3" class="radio" value="1"/>
        <label for="radio3">Milk</label>
    </div>
    </div>

    <div>
    </br>
    <div><div>
    <button type="button" onclick="hp(this.form)">Check</button>
    <input class="reset" type="reset" value="Reset">
    </div></div></div>
</form>
    <div id="result"></div>
    <div id="total"></div>
</body>
</html>

这是javascript

function hp(form)
{
var count1=0, count2=0, count3=0, count4=0, count5=0, count6=0, count7=0, count8=0, count9=0, count10=0,a ;
for(var i=0;i<3;i++){
if (form.q1[i].checked === true)
{
count1++;
}
}
if(count1!==1){
alert("Please Answer 1st Question");
return false;
}
answer1 = (form.q1.value);
a=Math.floor(answer1);
document.getElementById("result").innerHTML= "The selected values are "+"</br>"+answer1;
}

1 个答案:

答案 0 :(得分:0)

你应该声明一个答案变量。你应该访问&#34; q1&#34;元素通过给出索引,因为你有3&#34; q1&#34; elements .basically form.q1object NodeList。你无法从object NodeList获取价值。所以实际上在你的情况下你应该为for循环添加制动并找到点击的单选按钮索引

你应该使用

answer1 = form.q1[i].value;

而不是

answer1 = form.q1.value;

<小时/> 解释

form.q1object NodeList所以

form.q1.value --> undefined since object NodeList/collection has no property "value"

form.q1[0] --> HTMLInputElement so

form.q1[0].value --> is not undefined 

固定代码。WORKING DEMO http://jsfiddle.net/madhawa11111/3rywkdvf/

function hp(form) {
    var i;
    var answer;
    var count1 = 0,count2 = 0,count3 = 0,count4 = 0,count5 = 0,count6 = 0,count7 = 0,count8 = 0,count9 = 0,count10 = 0, a;

    for (i = 0; i < 3; i++) {
        if (form.q1[i].checked === true) {
            count1++;
            break;
        }
    }
    if (count1 !== 1) {
        alert("Please Answer 1st Question");
        return false;
    }
    answer1 = form.q1[i].value; //error was here .
    a = Math.floor(answer1);
    document.getElementById("result").innerHTML = "The selected values are " + "</br>" + answer1;
}

如果它在google chorm中有效,那是因为浏览器忽略了一些错误。