How to use Attribute Selectors In JQuery
By assigning a common attribute (e.g., data-button-type) to buttons, jQuery’s attribute selector efficiently captures click events on all buttons sharing that attribute. This example demonstrates the uniform handling of click events, providing a flexible approach for selecting and executing actions on buttons with shared attributes within a toolbar.
Example: To demonstrate utilizing JQuery, a click event handler is assigned to all buttons sharing this attribute which displays an alert when a button is clicked.
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 data-action = "btnAction1" >Button X</ button > < button data-action = "btnAction2" >Button Y</ button > < button data-action = "btnAction3" >Button Z</ button > < script > $(document).ready(function () { $("button[data-action]").click(function () { var btnAction = $(this).data("action"); alert(btnAction + " 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
});
});