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

Asked

Viewed 975 times

4

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

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

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

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

By clicking on (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 when selecting will generate an HTML with Radio Button for filters and by selecting a filter it gives a alert() displaying the filter value. The problem is that the alert is not running because I think it is because it is added by $("#meusfiltros").html('codigo-html-aqui'); . Now if I click on a link with the same div #filter it displays smoothly as it was already on the page at the time it uploaded.

1 answer

4


Exactly how you suspect here need to delegate the event of this $("a#filtro").click( because it didn’t exist yet when that code was read.

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

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

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

I suggest you take a look at this answer: /a/5199/129 about the difference of using the .on() and delegation of events.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.