0

I am trying to get a click event on the .clearBtn buttons. I tried the below code, but still no luck!!

<div id="job_city" class="filter-multi-select dropdown" tabindex="-1">
   <div class="viewbar form-control dropdown-toggle">
        <span class="placeholder" hidden="">Select option</span><span class="selected-items">
       <span data-id="job_city-1" class="item">Option 1<button type="button" class="clearBtn" tabindex="-1">×</button></span>
      <span data-id="job_city-0" class="item">Option 2<button type="button" class="clearBtn" tabindex="-1">×</button></span>
      </span>
    </div>

Here is the code I tried:

$(".clearBtn").click(function(e) {
    console.log('clear Btn clicked');
});

I should mention that the buttons are dynamically created and added to dom based on select options.

Kjobber
  • 176
  • 1
  • 9

1 Answers1

1

I should mention that the buttons are dynamically created and added to dom based on select options.

In which case, you'll need to use event delegation.

$(document).on("click", ".clearBtn", function(e){
   ...
});

Understanding Event Delegation | jQuery Learning Center

Richard Deeming
  • 29,830
  • 10
  • 79
  • 151
  • I tried this but still didn't work! I am using this plugin that creates the buttons https://github.com/andreww1011/filter-multi-select – Kjobber Feb 18 '22 at 16:31
  • @Kjobber this would suggest something else is bound to them or something is disrupting the click event. Please Update your post and include a Minimal, Reproducible Example: https://stackoverflow.com/help/minimal-reproducible-example – Twisty Feb 18 '22 at 16:33