所以我有一张表格。在这种形式下,我有一个单选按钮:
<span>
<label>
<input type="radio" name="mature" value="0">
All Ages
<span class="checkmark"></span>
</label>
<label>
<input type="radio" name="mature" value="1">
18+
<span class="checkmark"></span>
</label>
</span>
但是,在我对此表单的JS验证中,我注意到在Internet Explorer中,此单选按钮始终会返回错误。
if (document.forms["imageSubmit"]["mature"].value == "" || document.forms["imageSubmit"]["mature"].value == null) {
alert(document.forms["imageSubmit"]["mature"].value);
return false;
}
因此,例如在这种情况下,警报将始终返回&#34; undefined&#34;。但是,再次,只在互联网浏览器。
为什么会这样?
编辑:
感谢您的重定向。我已经调整了我的代码:
var mature = document.getElementsByName('mature');
var matureValue = false;
for(var i=0; i<mature.length;i++){
if(mature[i].checked == true){
matureValue = true;
}
}
if(!matureValue){
alert("Please fill the Viewing Restrictions field.");
return false;
}
答案 0 :(得分:3)
您有多个具有相同名称的元素。
document.forms["imageSubmit"]["mature"]
是一个集合,而不是单个元素。
你需要循环它(就像一个数组),直到你拥有一个真正的checked
属性。
在HTML 5中,radio buttons are special cased因此它们的集合将拥有自己的value
属性,表示当前选中的单选按钮。 Internet Explorer太旧而无法支持此功能。