0

我必须验证是否检查了radiobox。Javascript radiobutton在FF和Chrome中工作,但不在IE中

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; 
}​ 

回答

2

假设你正在使用jQuery,你可以这样做:

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

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

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

你没有表现出很大的HTML的,但是从你的JS它看起来像单选按钮id为“单选按钮”的元素里面,所以你可能要包括在您的jQuery选择:

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

如果您正在使用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处理formcollections与普通数组不同。以下代码在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);  
} 

0 
1 
----- 
0 
1 
length 
item 

IE

0 
1 
------------ 
rdio 
length 
item 
namedItem 
循环中的

通常会导致在javascript imo中出现问题,像jquery的每个一样使用助手,或者像上面的示例中那样执行常规for循环。

+0

+1。是的,从不使用'for..in'来迭代类似数组的对象(即具有'.length'属性和数字索引的对象)。一个简单的for循环或jQuery的$ .each()是要走的路(或['Array.forEach()'](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/ Array/forEach)如果你有一个实际的数组,而不仅仅是一个类似数组的对象)。 – nnnnnn 2012-03-24 23:49:21

相关问题