Passing a dynamic parameter to a JavaScript function using innerHTML

I'm having trouble passing a dynamic parameter to a JavaScript function using innerHTML.

Below is the current code I'm 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 variable name is null .

I believe that there is a problem with declaring a value when changing the innerHTML property.

Any help would be greatly appreciated.

thanks

+4
source share
5 answers

I just used onclick = "closeTab (name);" > in innerHTML and it worked. I think the working name coz is a global variable.

-1
source

The code you received is:

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

Do you see what happened? test treated as a variable when you actually assumed it was a string.

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

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

Use this in your button, not just test .

+3
source

Your dynamic declaration passes the parameter as a variable, not the value of the parameter. To fix this problem, you should pass the value as a string instead of a variable that is executed by including and excluding this variable in single quotes, as shown below:

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

Using DOM:

 var name="test"; var el = document.createElement("button"); el.name = "close"; el.id = "close"; el.title = "Cancel"; el.type = "button"; el.onclick = function() { // an inline function that will be executed when el is clicked closeTab(name); // `name` here contains `"test"` }; frm.appendChild(el); 

I really do not encourage excessive use of innerHTML , as it is messy, and may someday be slow.

0
source

Assuming your html is

 <form id='frm'> </form> 

Your JS should be -

 var name = "test"; var innerHtml = "<button name='close' id='close' title='Cancel' type='button'>Return</button>"; $("#frm").html(innerHtml); $("#close").attr("onclick","javascript:closeTab('"+name+"');"); 

Check it out - http://jsfiddle.net/arindam006/avgHz/1/

This is the cleanest way to achieve this, although innerHtml is not the right way to do this, as everyone suggested above.

0
source

All Articles