JavaScript,radiobutton.checked无法在IE中运行

时间:2015-11-06 04:38:50

标签: javascript html internet-explorer

我正在使用一些JavaScript来检查HTML表单,以查看用户是否选择了单选按钮。它在Chrome,FireFox和Safari中运行得非常好,但在IE中却没有(在不同的机器上尝试了ie9和ie11)。

以下是该页面的链接(它是学校作业的一部分,因此所有代码都可以在源代码中轻松查看),因此您可以查看代码并查看它在Chrome中的工作情况,看看IE中会发生什么。 http://lampbusters.com/bellerose/javascript/form.html (表单提交了一个简单的echo php脚本,因此您不必担心它会发送到任何地方或保存任何信息。)

对于那些不想关注此链接的人,请输入以下代码:

window.onload = setupEvents;
function setupEvents() {
document.getElementById('contactForm').onsubmit = checkForm;
}

function checkForm () {
var shootType = document.contactForm.shootType
var shootInstruct = document.getElementById('shootInstruct')
var checkOne = false;
var i;
for (i in shootType) {
  if (shootType[i].checked) {
    checkOne = true;
  }
}
  if (checkOne != true) {
    alert("Please tell me what kind of photography shoot you're interested in.");
    shootInstruct.style.color = "#FF0000";
    shootInstruct.style.fontSize = "1.2em";
    shootInstruct.style.fontWeight = "Bold";
    return false;
  }
  else {
    return true;
  }
}

shootType引用了大约6个带有相同"名称"的单选按钮。 HTML中的属性,因此它基本上用作数组。正如您所看到的,这只是通过该数组运行,检查是否检查了一个,然后提交表单(如果有人选中)或者如果没有提交则不提交。在所有其他浏览器中完美运行,但在IE中它永远不会提交,即使选中单选按钮也是如此。由于我只是在学习js,我不确定IE的哪一部分没有得到IE的支持,并且在搜索问题时没有多少运气。任何人都知道为什么这不在IE中工作?

1 个答案:

答案 0 :(得分:0)

不要在列表中使用 for..in ,使用标准for循环。在IE中,列表具有您不期望的其他可枚举属性:



var controls = document.forms[0].r;
for (var p in controls) document.write('"' + p + '"<br>');
&#13;
<form>
  <input type="radio" name="r">
  <input type="radio" name="r">
  <input type="radio" name="r">
  <input type="radio" name="r">
</form>
  
&#13;
&#13;
&#13;