JavaScript无法使用IE Edge浏览器检索值或长度

时间:2017-09-28 21:37:14

标签: javascript html

我正在尝试使用JavaScript获取表单中输入的值和长度。这适用于Chrome和Firefox,但不适用于Edge浏览器。对于本演示,我使代码尽可能简单。 Edge返回值“undefined”,然后明显炸弹获取长度(不警报或返回false)。控制台显示没有错误。只显示HTML1300:导航已经发生。

function CheckFields() {
  alert('The value is |' + document.trantype.joinselect.value + '|');
  alert('The length is |' + document.trantype.joinselect.value.length + '|');
  return false;
}
<form name="trantype" style="display: inline;" action="#" method="post" onsubmit="return CheckFields()">
  <input type="radio" name="joinselect" value="Test_1">&nbsp;This is Radio 1<br />
  <input type="radio" name="joinselect" value="Test_22">&nbsp;This is Radio 2<br />
  <input type="radio" name="joinselect" value="Test_333">&nbsp;This is Radio 3<br /><br />
  <input type="submit" value="Submit">
</form>

任何建议都将受到赞赏。

2 个答案:

答案 0 :(得分:0)

使用document.querySelector()

代替将表单元素作为属性访问的古老方法

&#13;
&#13;
function CheckFields() {
  var button = document.querySelector("form[name=trantype] input[name=joinselect]:checked");
  if (button) {
    alert('The value is |' + button.value + '|');
    alert('The length is |' + button.value.length + '|');
  } else {
    alert('No button is selected');
  }
  return false;
}
&#13;
<form name="trantype" style="display: inline;" action="#" method="post" onsubmit="return CheckFields()">
  <input type="radio" name="joinselect" value="Test_1">&nbsp;This is Radio 1<br />
  <input type="radio" name="joinselect" value="Test_22">&nbsp;This is Radio 2<br />
  <input type="radio" name="joinselect" value="Test_333">&nbsp;This is Radio 3<br /><br />
  <input type="submit" value="Submit">
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以尝试使用旧的IE也可以正常使用它。

var elem = document.querySelector("form[name=trantype]")
	if(elem.addEventListener){
		elem.addEventListener("submit", callback, false);  //Modern browsers
	}else if(elem.attachEvent){
		elem.attachEvent('onsubmit', callback);            //Old IE
	}

    function callback(e) {
		e.preventDefault();
		alert('The value is |' + document.trantype.joinselect.value + '|');
		alert('The length is |' + document.trantype.joinselect.value.length + '|');
		return false;
	}
<!DOCTYPE html>
<html>
  <head>
    <title>Test of Edge browser</title>
  </head>
  <body>
    <form name="trantype" style="display: inline;" action="#" method="post">
      <input type="radio" name="joinselect" value="Test_1">&nbsp;This is Radio 1<br />
      <input type="radio" name="joinselect" value="Test_22">&nbsp;This is Radio 2<br />
      <input type="radio" name="joinselect" value="Test_333">&nbsp;This is Radio 3<br /><br />
      <input type="submit" value="Submit">
    </form>
  </body>
</html>