【问题标题】:document.forms.value returning "undefined" only in IEdocument.forms.value 仅在 IE 中返回“未定义”
【发布时间】:2018-07-25 11:52:30
【问题描述】:

所以我有一个表格。在这种形式中,我有一个单选按钮:

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

因此,例如在这种情况下,警报将始终返回“未定义”。但是,同样,仅在 Internet Explorer 中。

为什么会这样?

编辑:

感谢您的重定向。我已经像这样调整了我的代码:

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

【问题讨论】:

标签: javascript html


【解决方案1】:

您有多个具有相同名称的元素。

document.forms["imageSubmit"]["mature"] 是一个集合,而不是单个元素。

您需要循环遍历它(如数组),直到您找到具有真正 checked 属性的那个。

在 HTML 5 中,radio buttons are special cased 因此它们的集合将具有自己的 value 属性,表示当前选中的单选按钮。 Internet Explorer 太旧,无法支持此功能。

【讨论】:

  • 啊。这就说得通了。也许我们都可以聚在一起,共同谋杀 Internet Explorer?
  • Internet Explorer 已经死了。只是它的一些用户还没有意识到这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多