I was trying to pass a string to a JavaScript function.
As it's mentioned here - Pass a string parameter in an onclick function
I'm using 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 it's giving an error like Uncaught SyntaxError: Unexpected token }
.
A JavaScript function does not perform any checking on parameter values (arguments).
In Pass by Reference, a function is called by directly passing the reference/address of the variable as the argument. Changing the argument inside the function affects the variable passed from outside the function. In Javascript objects and arrays are passed by reference.
Use the onclick attribute in a button tag with the function name and pass value in this function. With this method, you can also take input from users and pass parameters in the JavaScript function from HTML.
Change your code to
document.write("<td width='74'><button id='button' type='button' onclick='myfunction(\""+ name + "\")'>click</button></td>")
Rename your variable name
to myname
, bacause name
is a generic property of window
and is not writable in the same window.
And replace
onclick='myfunction(\''" + name + "'\')'
With
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With