'How can I get a JQuery click listen for this button

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.



Solution 1:[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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Richard Deeming