In jQuery, you can trigger the onclick
function of an element by using the click()
method. This method simulates a click event on the specified element, which in turn triggers the bound onclick
function.
The basic syntax for the click()
method is as follows:
$(selector).click();
Here, the $
symbol is used to represent the jQuery library, and the selector
is the HTML element on which the click event should be triggered.
Onclick function in jQuery example
Simple example codes Jquery With Button Onclick Function.
<!DOCTYPE html>
<html>
<head>
<title>Example - Onclick function in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$('#myButton').click(function(){
alert('Button clicked');
});
});
</script>
</head>
<body>
<button id="myButton">Click me</button>
</body>
</html>
Output:
Another example of using the onclick
function in jQuery:
<!DOCTYPE html>
<html>
<head>
<title>Example - Onclick function in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$('#myButton').click(function(){
$('p').text('Button clicked');
});
});
</script>
</head>
<body>
<button id="myButton">Click me</button>
<p>Click the button to change this text</p>
</body>
</html>
Do comment if you have any doubts or suggestions on this jQuery topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version