Passing a string parameter in a JavaScript function

I tried to pass a string to a javascript function.

As already mentioned, pass a string to the onclick function

I use this simple code -

<!DOCTYPE html> <html> <body> <script> name = "Mathew"; document.write("<button id='button' type='button' onclick='myfunction(\''" + name + "'\')'>click</button>") function myfunction(name) { alert(name); } </script> </body> </html> 

But in the console, this gives an error, like Uncaught SyntaxError: Unexpected token } .

+4
source share
4 answers

Change your code to

 document.write("<td width='74'><button id='button' type='button' onclick='myfunction(\""+ name + "\")'>click</button></td>") 
+3
source

Rename the variable name to myname , bacause name is a common property of window and cannot be overwritten in the same window.

And replace

 onclick='myfunction(\''" + name + "'\')' 

FROM

 onclick='myfunction(myname)' 

Working example:

 var myname = "Mathew"; document.write('<button id="button" type="button" onclick="myfunction(myname);">click</button>'); function myfunction(name) { alert(name); } 
+6
source

The answer to this question was given, but for your future coding reference, you could consider this.

In your HTML, add the name as an attribute to the button and remove the onclick link.

 <button id="button" data-name="Mathew" type="button">click</button> 

In your JS, grab the button using your identifier, assign a function to the click button, and use the function to display the attribute of the name of the button name.

 var button = document.getElementById('button'); button.onclick = myfunction; function myfunction() { var name = this.getAttribute('data-name'); alert(name); } 

Good luck.

Demo

+1
source
 //use this document.write('<td width="74"><button id="button" type="button" onclick="myfunction('" + name + "')">click</button></td>') 
0
source

All Articles