Javascript - onsubmit for dynamically created forms not executing function

3589 views javascript
9

I have a button that on clicking generates a new form with multiple input boxes (with dynamically generated IDs for each element as well). Each form has a submit button. The form when submitted executes a function.

<form id='f1' name='form1' onsubmit='return myFunction("1");'>

This is a default form that's already present in the page and it works fine.

For the dynamically added form, I set the attribute for onsubmit like:

var f = document.createElement("form");
var fn = "f"+number_inserted_dynamically;
var funname = "return myFunction(\""number_inserted_dynamically"\");";
f.setAttribute('onsubmit',funname);

This is what I found when I inspected the element on Chrome (for the generated form):

<form id="f2" onsubmit="return myFunction("2");">

But the function isn't getting executed.

As seen in one of the other questions, I tried using

f.onsubmit = myFunction; (with number_inserted_dynamically defined inside myFunction)

which didn't work either.

What's going wrong? How else do I set onsubmit dynamically for the function?

answered question

2 Answers

13

<form id="f2" onsubmit="return myFunction("2");"> is a syntax error due to the quotes. Your onsubmit will evaluate to return myFunction( and then throw a syntax error.

Instead of:

var funname = "return myFunction(\""number_inserted_dynamically"\");";

You'll want:

var funname = "return myFunction('number_inserted_dynamically');";

So that you end up with:

<form id="f2" onsubmit="return myFunction('2');">

However, you really should make use of Unobtrusive JavaScript, and instead use an event listener:

f.addEventListener("submit", return myFunction('2'));

posted this
0

If jQuery:

var eleForm = $('<form>...</form>');

$('body').append(eleForm); // append the form to body

eleForm.on('submit', function() {
   // here to put your code about submitting form
});

posted this

Have an answer?

JD

Please login first before posting an answer.