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?
<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.
var funname = "return myFunction(\""number_inserted_dynamically"\");";
var funname = "return myFunction('number_inserted_dynamically');";
So that you end up with:
<form id="f2" onsubmit="return myFunction('2');">
f.addEventListener("submit", return myFunction('2'));