Polymer: manually submitting a form
Asked Answered
C

2

6

In polymer I'm trying to manually submit a form. My form looks like this:

<form id="myForm" on-submit="{{ submitForm }}">
    <input class="text" value="{{ someValue}}">
    <button type="submit">Submit</button>
</form>

And in the polymer object I have:

submitForm: function(e) {
    e.preventDefault();
}

Whenever I try to do the following:

document.getElementById('myForm').submit();

the form totally ignores the on-submit attribute and posts the form to a new page.

I'm building a on-screen keyboard for anyone wondering why I would want to do this. I need to submit the form whenever someone hits the enter key on the on-screen keyboard.

Does anyone know why this happens?

A JSBin example to show you the exact problem (see the alerts): http://jsbin.com/wadihija/2/

Crackerjack answered 18/4, 2014 at 10:3 Comment(0)
R
5

From the MDN page about submit:

The form's onsubmit event handler will not be triggered when invoking this method ... it is not guaranteed to be invoked by HTML user agents.

However, calling click on a submit type button seems to work. See here:

http://jsbin.com/tuxac/2/edit

Here is a modification of your jsbin that I believe does what you want:

http://jsbin.com/wadihija/6/edit

Reid answered 23/4, 2014 at 17:42 Comment(1)
Thanks alot for your research! I've been so used to using jQuery for submitting forms that manually submitting a form seemed so default for me..Crackerjack
S
1

Is this along the lines of what you're trying to do? This is a result of a key feature of Shadow DOM: Encapsulation. The elements in your polymer-element's template are not in the main document, and as such, are not available via document.getElementById() and the like.

You could instead call this.shadowRoot.getElementById() and it would work because this inside of your polymer-element's prototype is linked to the host element. Or even better, take advantage of the amazing features Polymer gives you for free. Polymer exposes this.$ to polymer-elements, which contains a key for every element in your template that has an ID! No method call needed, just use this.$.myForm.submit(). Here's the final jsbin.

Solidary answered 18/4, 2014 at 17:31 Comment(2)
Hey thanks for your reply, the problem you are describing is not the problem i'm having. I've made a jsbin example showing you a simplified version of my problem. It's basicly manually submitting a form from a parent component.Crackerjack
Wow, that is really weird behavior. If I could upvote your question again I would :)Solidary

© 2022 - 2024 — McMap. All rights reserved.