In this tutorial, we will learn how to use jQuery’s onclick event to call a function and pass parameters, including the element’s ID. This can be very useful when you want to trigger specific actions for different elements on a webpage.
jQuery onclick Call Function with Parameters, id, data attribute value Example
Steps to onclick call function with parameters, id, data, attribute etc in jquery:
- Step 1: Setting up the HTML structure
- Step 2: Including jQuery in your project
- Step 3: Creating the JavaScript function
- Step 4: Using the
onclick
event to call the function with parameters
Step 1: Setting up the HTML structure
First of all, we need to create a basic HTML structure with elements that we can interact with. In this example, we’ll create buttons with unique IDs and a container to display the result.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery onclick Function Example</title>
</head>
<body>
<button id="btn1">Button 1</button>
<button id="btn2">Button 2</button>
<div id="result"></div>
<!-- Include jQuery library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Include your custom JavaScript file -->
<script src="script.js"></script>
</body>
</html>
Step 2: Including jQuery in your project
Now, we need to include jqueyr in project. So,We’re using a Content Delivery Network (CDN) to include jQuery in our project. You can also download jQuery and host it locally. Make sure the jQuery script tag is placed before your custom JavaScript file.
Step 3: Creating the JavaScript function
Then, we need to create a JavaScript file called script.js
and define the function that will be called when the buttons are clicked. This function will take the element’s ID as a parameter and display a message in the result container.
// script.js
// Function to handle button clicks
function handleButtonClick(buttonId) {
// Generate a message based on the button's ID
var message = "Button with ID '" + buttonId + "' was clicked!";
// Display the message in the result container
$("#result").text(message);
}
Step 4: Using the onclick
event to call the function with parameters
In the last steps, we will use the jQuery onclick
event to call the handleButtonClick
function when a button is clicked. We will also pass the button’s ID as a parameter.
// script.js
$(document).ready(function() {
// Attach click event handlers to the buttons
$("#btn1").click(function() {
handleButtonClick("btn1");
});
$("#btn2").click(function() {
handleButtonClick("btn2");
});
});
In this code, we’re using the .click()
method to attach a click event handler to each button. When a button is clicked, the corresponding function (handleButtonClick
) is called, passing the button’s ID as a parameter.
Conclusion
Congratulations! You’ve learned how to use jQuery’s onclick
event to call a function with parameters, including the element’s ID.