-1

In my project i create using Ajax DOM a POST form. I have to add an onsubmit method, i try:

var impform = document.createElement("FORM");
impform.method = "post";
impform.onsubmit = "/import_templ";

but wher i load my webpage form are created ok and method was POST but there isn't the onsubmit method.

enter image description here

How can i add my onsubmit method to the form?

Thanks in advance

Manuel Santi
  • 1,106
  • 17
  • 46
  • `onsubmit` is a method, here you have assigned it to a string, so it cannot be executed. Perhaps you mean to use `action` instead of `onsubmit`? – Nick Parsons Feb 20 '19 at 13:25
  • Possible duplicate of https://stackoverflow.com/questions/13849659/adding-onsubmit-to-a-form-via-javascript – Mirakurun Feb 20 '19 at 13:26

3 Answers3

0

The value assigned to the onsubmit property (or attached with addEventListener, which is the modern approach) needs to be a function.

You are assigning a string.

function submitHandler(e) {
    e.preventDefault();
    document.body.style.background = '#aaf';
}

var impform = document.createElement("form");
impform.method = "post";
impform.action = "http://example.com/";
impform.addEventListener("submit", submitHandler);

var btn = document.createElement("input");
btn.type="submit";

impform.appendChild(btn);
document.body.appendChild(impform);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

for example. DOM form/input access and click button submit.

<form method="post" name="form_test">
  <button type="button" name="submit_test" >test</button>
</form>
<script>
document.form_test.method = "post";
document.form_test.action = "/import_templ";
document.form_test.addEventListener("click", submit);
function submit () {
  document.form_test.submit();
}
</script>
kaikusakari
  • 13
  • 2
  • 5
-2

In believe that /import_templ is the road you want to access so you have to put this in the action of the form not onsubmit

impform.method = "/import_templ";

then change you button type to "submit" IMPORT THIS TEMPLATE

goupil
  • 175
  • 10