Press "Enter" to skip to content

[Resolved] String is not defined in Passing string Parameter in JavaScript function

If you pass a string variable in your JavaScript function, then you may get error of ‘String is not defined’.

Because javascript taken your string as a variable.

 <script>
            testName = "YourOwnCode.com";
            document.write("<button id='button' type='button' onclick='TestFunction(" + testName + ")'>Open</button>")

            function TestFunction(name)
            {
                alert(name);
            }
        </script>

Above code will not work.

So you need to make the variable as a string type by giving enough quotes and escape slashes.

Working Code:

 <script>
            testName = "YourOwnCode.com";
            document.write("<button id='button' type='button' onclick='TestFunction(\""+ testName + "\")'>Open</button>")

            function TestFunction(name)
            {
                alert(name);
            }
        </script>

Be First to Comment

Leave a Reply