How to use Button Classes In JQuery
Assigning a common class to multiple buttons simplifies event handling in jQuery. By sharing a class, one can efficiently capture click events on all corresponding buttons. This approach enhances code organization and promotes a streamlined method for executing actions consistently across the buttons within the specified class.
Example: Capturing click events on toolbar buttons using shared class on buttons.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" /> < title >Toolbar Button Click</ title > < script src = "https://code.jquery.com/jquery-3.6.4.min.js" > </ script > </ head > < body > < button class = "toolbar-btn" >Button A</ button > < button class = "toolbar-btn" >Button B</ button > < button class = "toolbar-btn" >Button C</ button > < script > $(document).ready(function () { $(".toolbar-btn").click(function () { var btnText = $(this).text(); alert(btnText + " clicked!"); }); }); </ script > </ body > </ html > |
Output:
How to Capture Click Events on Selected Toolbar Buttons Using jQuery ?
When working with web applications and interfaces, capturing click events on toolbar buttons is a common task. jQuery simplifies this process by providing a convenient way to handle such events. There are several approaches for capturing click events on toolbar buttons using jQuery which are as follows:
Table of Content
- Using Button IDs
- Using Button Classes
- Using Attribute Selectors
Syntax:
$(document).ready(function(){
$("#buttonID").click(function(){
// Your code to be executed on button click
});
});