Form.submit is not found in Javascript

1

Code

html

<form id="myFrm" name="myFrm" action="/myApp/ProcessFrm" method="post">
    <input autofocus="autofocus" type="text" id="Location" name="Location" onkeydown="changetotab()" style="width: 4em" tabindex="1"  />
    <input type="Submit" value="Submit" id="submit" /> <br />
</form>

js

 function changetotab() {
            var charCode = (window.event.which) ? window.event.which : window.event.keyCode;

            if (charCode == 13 || charCode == 9) {
                if (document.myFrm.submit == undefined) {
                    alert("form submit can't be found")
                } else {
                    alert("form can be submitted");
                   document.myFrm.submit();
                }
            }
        }

What happens is that when the user pressed TAB or ENTER, document.myFrm.submit == undefined comes up false (so far so good); then something weird happens - when I get to document.myFrm.submit(); JS informs that this method is not found.

0x80020003 - JavaScript runtime error: Member not found.

What is happening here?

Note: I can't use Jquery, just in case you were wondering why I am using old style JS. This will run on the old devices that do not support Jquery.

javascript
forms
asked on Stack Overflow Apr 4, 2014 by sarsnake

2 Answers

10

See this JSfiddle. What's going on here? Well, in the pre-DOM times, JavaScript created one property foo for each input with name foo on the input's parent form:

form.foo.toString() === "HTMLInputElement";

This however, means, that, if you have an input element with name submit, the form's own submit method is overwritten. This behaviour has survived till today.

Now, your input has no name attribute. In this case, the behaviour is to deduce one from the input's ID, if one is set. So basically, change the ID of the input, that's the most straight-forward way to deal with it:

<input type="Submit" value="Submit" id="submit_" />

There are lots of such subtleties, unfortunately. See DOMLint for a good overview.

Edit: What to do, if you end up with a clobbered submit method and no way to change the HTML? Then fetch the submit method from the form's prototype and use that:

// form.submit() doesn't work, but this will:
HTMLFormElement.prototype.submit.call(form);
answered on Stack Overflow Apr 4, 2014 by Boldewyn • edited Apr 19, 2017 by Boldewyn
0

Try this (plain javascript):

document.getElementById('myFrm')
answered on Stack Overflow Apr 4, 2014 by pj013

User contributions licensed under CC BY-SA 3.0