Javascript单选按钮可以在FF和Chrome中使用,但不能在IE中使用

Javascript radiobutton works in FF and Chrome but not in IE

本文关键字:IE 但不能 单选按钮 FF Javascript Chrome      更新时间:2023-09-26

我必须验证是否选中了单选框。

HTML

<input style="width:20px;" id="radio1" type="radio" name="benvoor" class="benvoor"  value="Ik ben voor" /> <label for="radio1">Ik ben voor. </label><br />
<input style="width:20px;" id="radio2" type="radio" name="benvoor" class="benvoor"  value="Ik ben tegen" /> <label for="radio2">Ik ben tegen.</label>

JavaScript/jQuery

//Assume no radio checked first
var benvoor = false;
for (i in aanmeldform.benvoor) {
    // Is the element checked?
    if (aanmeldform.benvoor[i].checked) {
        //Choice has been made
        benvoor = true;
        // Cancel the loop if the checked element is found
        break;
    }
}
// If no choice has been made, put it in the errorList
if (!benvoor) errorList.push("benvoor");
// Cancel submit if errors are found
if (errorList.length > 0) {
    document.getElementById("errorMessage").innerHTML = "Graag uw keuze maken";    
    $("#radiobutton label").addClass("rood");
    $("html, body").animate({
        scrollTop: $(this).offset().top
    }, 1000);
    return false;
}​

假设您使用的是jQuery,您可以执行以下操作:

if ($(':radio[name="benvoor"]:checked').length === 0) {
   // none are checked, do something
}

也就是说,查找所有选中的该名称的单选按钮,如果生成的jQuery对象的长度为0,则不选中任何单选按钮。

简单演示:http://jsfiddle.net/WKKby/

您没有显示太多的html,但从JS来看,单选按钮似乎位于id为"radiobutton"的元素中,因此您可能希望将其包含在jQuery选择器中:

if ($('#radiobutton :radio[name="benvoor"]:checked').length === 0) {

如果您仍在使用jquery,可能会使用@nnnnnn答案,但您的代码在jsFiddle中略有修改:http://jsfiddle.net/p9bs3/5/

var benvoor = false;
for (var i =0;i < aanmeldform.benvoor.length;i++) {
    // Is the element checked?
    if (aanmeldform.benvoor[i].checked) {
        //Choice has been made
        benvoor = true;
        // Cancel the loop if the checked element is found
        break;
    }
}

IE处理的表单集合似乎不同于常规数组。以下代码在chrome和IE中产生两种不同的结果。

<form id="frm">
    <input type="radio" name="rdio">
    <input type="radio" name="rdio">
</form>

脚本:

var arr = [1,2];
for(i in arr){
    console.log(i);    
}
console.log('-----');
for(i in frm.rdio){
    console.log(i);    
}

Chrome

0
1
-----
0
1
length
item

IE

0 
1 
------------ 
rdio 
length 
item 
namedItem 

因为内循环通常是JavaScriptimo中出现问题的原因,所以请使用像jquery的each这样的助手,或者像上面的例子一样执行常规的for循环。

相关文章: