user3123833
user3123833

Reputation: 23

Javascript document.forms value does not work for Internet Explorer

I have searched high and low and I cannot figure out why this code works for Chrome/FF but will not work for IE.

function validateForm() {
    var x = document.forms["myForm"].elements["fname"].value;
    if (x == null || x == "") {
        alert("Name must be filled out");
        return false;
    }
}
<body>

<form name="myForm" action="/action_page_post.php"
onsubmit="return validateForm()" method="post">
<input type="radio" name="fname" id="fname" value="1">1
<input type="radio" name="fname" id="fname" value="2"> 2
<input type="submit" value="Submit">
</form>

</body>

See working demo here: https://www.w3schools.com/code/tryit.asp?filename=FEBA861EAACS

Works on Chrome by not IE

Upvotes: 2

Views: 4440

Answers (1)

gaetanoM
gaetanoM

Reputation: 42054

For the first I would suggest to have different IDs for fìdifferent elements

The value attribute is not supported in IE.

elements: The HTMLFormElement.elements property returns an HTMLFormControlsCollection (HTML 4 HTMLCollection) of all the form controls contained in the FORM element, with the exception of input elements which have a type attribute of image.

You can access a particular element by using either an index or the element name or id.

Because you have two radio:

document.forms["myForm"].elements["fname"]

returns a collection (nodelist) not a value. So, you must filter the collection:

function validateForm() {
        var x = Array.from(document.forms["myForm"]
           .elements["fname"]).filter(function(ele, idx) {
        return ele.checked;
    });
    if (x.length == 0) {
        alert("Name must be filled out");
        return false;
    }
}

A different solution can be based on a different selection strategy:

[document.querySelector('[name="myForm"] [name="fname"]:checked')][2]

The snippet:

function validateForm() {
  var x = document.querySelector('[name="myForm"] [name="fname"]:checked');
  if (x == null) {
      alert("Name must be filled out");
      return false;
  }
}
<form name="myForm" action="/action_page_post.php"
      onsubmit="return validateForm()" method="post">
    <input type="radio" name="fname" id="fname1" value="1">1
    <input type="radio" name="fname" id="fname2" value="2"> 2
    <input type="submit" value="Submit">
</form>

Upvotes: 4

Related Questions