How to Pass string parameter in an onclick function
By FoxLearn 2/14/2025 8:28:47 AM 952
For example, html onclick pass parameter
<a href="#" onclick="return getByCustomerID('+ item.customerID + ')">Edit</a>
If customerID is a string
ex. 'ABCD', 'XYZS'
You will get an error when passing value to onclick function
html render
<a href="#" onclick="return getByCustomerID(ABCD)">Edit</a>
To solve the problem, You just need to add some quotes around item.customerID
You can modify your code as shown below.
<a href="#" onclick="return getByCustomerID(\''+ item.customerID + '\')">Edit</a>
How to pass parameters to a function using the onclick
event?
In JavaScript, you can pass parameters to a function when using the onclick
event handler.
For example, Passing a string parameter
<!-- javascript function string parameter --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript onclick with Parameter</title> <script> function greet(name) { alert('Hello, ' + name); } </script> </head> <body> <button onclick="greet('Alice')">Click Me</button> </body> </html>
In this example:
- When the button is clicked, it calls the
greet()
function, passing'Alice'
as the parameter. - The
greet
function will display an alert message withHello, Alice
.
For example, Passing multiple parameters
<!-- html onclick function with parameters --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Multiple Parameters</title> <script> function showDetails(name, age) { alert('Name: ' + name + ', Age: ' + age); } </script> </head> <body> <button onclick="showDetails('John', 25)">Click Me</button> </body> </html>
For example, Passing a dynamic value
<!-- html onclick with parameter --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamic Parameter Example</title> <script> function displayMessage(message) { alert(message); } </script> </head> <body> <input type="text" id="userInput" placeholder="Type something..."> <button onclick="displayMessage(document.getElementById('userInput').value)">Submit</button> </body> </html>
This example grabs the value entered in the input field using document.getElementById('userInput').value
and passes it to the displayMessage()
function when the button is clicked.
- How to convert voice to text in Javascript
- LET vs VAR in JavaScript Variable Declarations
- How to add voice commands to webpage in Javascript
- How to capture an image in javascript
- How to Build Your Own JavaScript Library
- How to reverse a string properly in Javascript
- How to bypass 'Access-Control-Allow-Origin' error with XMLHttpRequest
- What is Hoisting in JavaScript