Passing Strings to JavaScript Functions (PSJF)

I am trying to pass a string to a JavaScript function. As mentioned here - Pass string parameter in 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 console it gives error like

Uncaught SyntaxError: Unexpected token }.

Solutip

Change your code to

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

Post a Comment

Previous Next

نموذج الاتصال