Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing dynamic parameter to a JavaScript function using innerHTML

I am having issues passing a dynamic parameter to a JavaScript function using innerHTML.

Included below is the current code that I am using:

var name = "test";

frm.innerHtml = '<button name="close" id="close" title="Cancel" type="button"
     onclick="closeTab('+name+');">Return</button>';

When I debug the code of the closeTab() function, the parameter specified by the name variable is null.

I believe there is a problem with the declaration of the value while modifying the innerHTML property.

Any help would be greatly appreciated.

Thanks

like image 712
Coder Avatar asked Jul 04 '12 03:07

Coder


2 Answers

Your dynamic declaration is passing the parameter as a variable, instead of the value of the parameter. In order to correct this issue, you must pass the value as a string, instead of a variable, which is accomplished by encasing and escaping the variable in single quotes as demonstrated below:

var name = "test";

frm.innerHtml = '<button name="close"  id="close"  title="Cancel" type="button"
      onclick="closeTab(\''+name+'\');">Return</button>';
like image 168
Robert Avatar answered Nov 14 '22 12:11

Robert


Your resulting code is:

<button ... onclick="closeTab(test);">Return</button>

Can you see what's wrong? test is being treated as a variable, when you actually intended it to be a string.

I like to use JSON.stringify to make a variable parseable (kind of like var_export in PHP), but in this case you also need to escape quotes. So:

JSON.stringify(test).replace(/"/g,"&quot;")

Use that in your button instead of just test.

like image 23
Niet the Dark Absol Avatar answered Nov 14 '22 13:11

Niet the Dark Absol