jQuery Click Event Handling

User
jQuery(".sorticon").on('click', function(e) {
alert("adsfd");

var sortcol = jQuery(this).data('col');
var sortorder = jQuery(this).data('sort');
$("#sortcol").val(sortcol);
$("#sortorder").val(sortorder);
search();
})
make above body with on

Assistant
You can use the `.on()` method in jQuery to handle events for multiple elements, and you can simplify the code using an arrow function for better readability. Here’s how you can rewrite the provided code using the `.on()` method for a more modern and concise approach:

$(document).ready(() => {
    $(document).on('click', '.sorticon', function(e) {
        alert("adsfd");

        const sortcol = $(this).data('col');
        const sortorder = $(this).data('sort');
        $("#sortcol").val(sortcol);
        $("#sortorder").val(sortorder);
        search();
    });
});

### Explanation:
– **`$(document).ready(() => {…})`**: Ensures the DOM is fully loaded before the script runs.
– **`$(document).on('click', '.sorticon', function(e) {…})`**: This binds the click event to any element with the class `sorticon`, even if they are added to the DOM after the page is loaded.
– **`const`**: Using `const` for `sortcol` and `sortorder` to define these variables as block-scoped and to indicate they won’t be reassigned.
– **`search()`**: This function call remains unchanged, as it appears to be part of your logic.

This code will alert "adsfd" whenever an element with the class `sorticon` is clicked, retrieve the necessary data attributes, set the values in the input fields, and then call the `search()` function.

Leave a Comment

Your email address will not be published. Required fields are marked *