Reputation: 79
I want to pass multiple parameters to a function that is called via onClick. Here is the code:
div.innerHTML += '<input type="button" name="back" id="back" value="Back" onClick="homeForm(\'' + form,divName + '\')" />';
function homeForm(form,divName){
//do something
}
This works with one parameter but not two:
div.innerHTML += '<input type="button" name="back" id="back" value="Back" onClick="homeForm(\'' + form + '\')" />';
Could someone post a working method for this, or perhaps a cleaner way?
Upvotes: 0
Views: 4827
Reputation: 1253
If you’re trying to pass data from a element to an onclick function, a straightforward approach is to pass the IDs of both elements. Then, within the function, retrieve the values associated with those IDs. This makes it easier to handle and evaluate the data.
div.innerHTML += '<input type="button" name="back" id="back" value="Back" onClick=\'homeForm("formId","divId")\' />';
function homeForm(formId,divId)
{
console.log($("#"+formId));
console.log($("#"+divId));
}
Upvotes: 2
Reputation: 79
So in the end this code was the only one that worked for me. I'm posting it here in case someone else needs it:
div.innerHTML += '<input type="button" name="back" id="back" value="Back" onClick="homeForm(\''+myForm+'\',\''+divName+'\')" />';
Upvotes: 4
Reputation: 12213
Easy! It looks like you have forgotten that the comma between form and divName should be enclosed in quotes. Instead of
...' + form,divName + '...
do
...' + form + ',' + divName + '...
Upvotes: 0
Reputation: 4539
Try below, Don't escape it. Concatenate params properly. like below:
div.innerHTML += '<input type="button" name="back" id="back" value="Back" onClick="homeForm(' + form + ',' + divName + ')" />';
Upvotes: 2