Search code examples
javascriptjqueryeventsdatatablestarget

Unable to trigger an evt when clicking on a specific button


I have three plus (+) buttons next to three separate tables (built with DataTables). Since the +s were created in one location (with DT), clicking on any of them opens the same modal. For the most part, they have the same DOM structure and classes.

I want to make it so that clicking on one of the +s does one thing, clicking on the second + does another thing, etc. There are slight differences in some of the IDs of the parents and I'm trying to use specificity to target specific +s.

I'm writing because I've been unable to target only one + (console.log's not working).

It's probably something pretty silly, but I've been tinkering with this and haven't had any luck, so I wanted to ask about it here.

JS snippet:

// $(document).on("click", ".btn-new", disp._newRole); // ----- this works, but it triggers every +

$(document).on("click", "#DataTables_Table_2_wrapper > .btn-group > .btn-default > .btn-new", disp._newRole);

$(document).on("click", "#DataTables_Table_2_wrapper > .btn-group > .btn-default > .btn-new", function() {
    console.log('hello')
});

Screencap:

#DataTables_Table_2_wrapper is unique. The two other tables use a 0 and 1 instead of a 2.

enter image description here

JS (where the + is created)

buttons: [
                {
                  text:      '<div class="btn btn-new" style="bottom:0.75rem; padding-right:2rem; position:relative;" title="Click to add new search"><i class="fa fa-plus"></i></div>',
                  titleAttr: 'Add',
                  exportOptions: {
                      columns: _colExport
                  }
                },

Solution

  • You miss a child in the target .btn-new

    $(document).on("click", "#DataTables_Table_2_wrapper > .btn-group > .btn-default > span > .btn-new > .fa-plus", function() {
    console.log('hello')});
    

    And i suggest you to declare a custom class and avoid too nested targets, as it can easily generates errors and decreases code readability.