Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing string parameter in JavaScript function

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 }.

like image 296
Anurag Chakraborty Avatar asked Aug 12 '15 09:08

Anurag Chakraborty


People also ask

Can JavaScript function accept parameters?

A JavaScript function does not perform any checking on parameter values (arguments).

Is there a pass function in JavaScript?

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.

How pass parameter from JavaScript to HTML?

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.


Video Answer


2 Answers

Change your code to

document.write("<td width='74'><button id='button' type='button' onclick='myfunction(\""+ name + "\")'>click</button></td>")
like image 191
Juned Lanja Avatar answered Sep 17 '22 19:09

Juned Lanja


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);
}
like image 36
Nina Scholz Avatar answered Sep 21 '22 19:09

Nina Scholz