2

I am trying to sharpen my vanilla JavaScript skills a little bit. I am working on a form validator just for fun. Here is my code thus far:

var getParent = document.getElementById("myForm");

document.getElementById("submit").onclick = function(e) {

e.preventDefault();

var cache = !cache ? "Nothing has been selected" : cache;

for(i = 0; i < getParent.elements.method.length; i++) {

    if(getParent.elements.method[i].checked) {
        cache = getParent.elements.method[i].value;
    }

}

getParent.submit();

}

As you can see, this just tests some radio buttons to see if they are checked or not. I am trying to use the .submit() function at the bottom to submit my form, but I am getting an error. Why is this code not submitting my form with .submit()??

6
  • 2
    What error are you getting? Commented Jan 9, 2013 at 19:20
  • Uncaught TypeError: Property 'submit' of object #<HTMLFormElement> is not a function Commented Jan 9, 2013 at 19:20
  • 2
    use another ID than "submit" for the button Commented Jan 9, 2013 at 19:25
  • altough this question is not related to jQuery, the issue is the same: Why do i get an exception when I use JQuery's form.Submit() in IE8? Commented Jan 9, 2013 at 19:27
  • I'd say it's not a duplicate. The question contains a different error message because the actual issue is different: he spelled it Submit instead of submit. I wouldn't have expected OP to have found that question by Googling the error message, so it's sufficiently different. Commented Jan 9, 2013 at 19:32

1 Answer 1

4

You can not have the button named submit and use submit().

The button will override the method. So, when you call getParent.submit() it actually points to the button, not the actual submit function.

Sign up to request clarification or add additional context in comments.

4 Comments

Some technical detail: forms allow you to access elements of the form by name, e.g., loginForm.username returns the username input field. So, while forms have a submit method by default, if a field named submit is present, it'll override the submit method. That's why submit is "not a function": in this case, it's a button.
Ahh, thank you sir. I forgot that we can overwrite methods pretty easily.
I've always found this "helpful" method of accessing form fields as properties of the form element to be highly intrusive. I get the intent, but it leads to bizarre bugs like this quite often.
@AlexWayne: It's an artifact of a previous era, when the DOM API was built around very specific tasks like form interaction. If we could get rid of all old websites and start the API from scratch, this feature probably wouldn't make the cut.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.