jQuery Click does not work on results coming from $ .post

4

I'm developing a delete button on the product form that I have, it works like this

  • Category 1 (Radio Button)
  • Category 2 (Radio Button)

After selecting a category, it sends a jQuery command to the $ post function and creates html elements in a part of the site with several radio button like this:

  • Filter 1 (DELETE)
  • Filter 2 (DELETE)
  • Filter 3 (DELETE)

When you click (DELETE) it has to execute a function with the following code

 $("a#filtro").click(function(){
        alert($(this).attr('valor'));
 });

That is, the client will select a category and selecting it will generate HTML with Radio Button for filters, and when selecting a filter it will alert() displaying the filter value. The problem is that the alert code is not running because I think it's because it's added by $("#meusfiltros").html('codigo-html-aqui'); . Now if I click on a link with the same div #filter it will display without problems as it was already on the page at the time you uploaded.

    
asked by anonymous 14.10.2014 / 07:09

1 answer

3

Just as you suspect here you need to delegate the event of this $("a#filtro").click( since it did not exist even when this code was read.

Since #meusfiltros already existed on the page when the code was read, then you can do this:

$("#meusfiltros").on('click', "#filtro", function(){
// ou mesmo (ainda mais seguro) 
$(document).on('click', "#filtro", function(){

The .on() method allows you to delegate the event for cases where the element is added dynamically (after the code has been run).

I suggest taking a look at this answer: link on the difference of using .on() and delegation of events.

    
14.10.2014 / 07:14