jquery click doesn't work on ajax generated content
Asked Answered
V

4

80

I am using $(".button").on("click", function(){ });

to click to a button which is on a container but then an ajax call is done and the content gets updated with new stuff and then when i try to click .button it wont work... nothing will get returned when i click the button.

I even tried

$(".button").live("click", function(){ });

or

$(".button").click(function(){ });

How can I make it work?

EDIT : my html:

<div class="container">
   <ul>
       <li>item1</li>
       <li>item2</li>
       <li>item3</li>
   </ul>
   <input type="button" value="reload" class="button" />
</div>
Vanover answered 18/2, 2012 at 21:37 Comment(3)
Please show What is being returned by the ajax call.Sulfuric
And the rest of jQuery that attaches the listener. What you're describing is exactly what live is supposed to handle, so it's strange that that isn't working.Numismatist
i have a ul where i click on them and simply echo "test" in javascript with .on("click") but when i click the button it will do an ajax call and reload the ul but then it will stop doing nothing when i click the button.. it wont return anything.Vanover
W
162

Should be done this way.

$('body').on('click', '.button', function (){
        alert('click!');
    });

If you have a container that doesn't change during the ajax request, this is more performant:

$('.container').on('click', '.button', function (){
        alert('click!');
    });

Always bind the delegate event to the closest static element that will contain the dynamic elements.

Wader answered 18/2, 2012 at 21:53 Comment(6)
Thanks for the answers! Still think this is very weird and doesn't feel allright to use this way. Wish jquery had a better way of handling these kind of situationsOsgood
@MiguelStevens, read on's docs once you read and understood the concept, it won't be weird and will make perfectly sense.Wader
But how would I write parent for this... $("input#someId").autocomplete({//some code});...there is no on event here..Glow
@Sadaquat, I suggest writing a full question with all the required details in a different thread. If you won't get an answer, you can ping me with a comment and I'll try my best to help.Wader
i did the same but its not working..any suggestions?Amputee
Finally I found the solution I was looking for! Thank you sirSit
V
41

Ok i solved my problem by using the .on() function correctly since i was missing one parameter.

instead of

$(".button").on("click", function() { } );

i used

$(".container").on("click", ".button", function() { } );
Vanover answered 18/2, 2012 at 21:51 Comment(4)
Just a note, the selector argument is not required, but is necessary in this case.Kamilahkamillah
Why is the selector argument not required, but necessary in this case?Dalton
I think it's because the selector is re-run in this case, but if not included it is not captured in the originally-run list of items grabbed with the selector.Unguiculate
@Vanover thanks man it really solved my tension.Synergist
V
8

Instead of:

$(".button").on("click", function() { } );

I used:

$(".container").on("click", ".button", function() { } );

I have used this and it worked.

Vary answered 3/4, 2013 at 11:52 Comment(0)
K
3

Is this what you're trying to do? Note, I'm putting the $.on() on the parent, but selecting the .button for the action.

.on( events [, selector] [, data], handler(eventObject) )

selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.

http://api.jquery.com/on/

<div id="stuff">
    <button class="button">Click me!</button>
    <p>Stuff</p>
</div>

var $stuff = $('#stuff'),
    ajaxContent = $stuff.html();

$stuff.on('click', '.button', function(){
    $.get('/echo/html/', function(){
        $stuff.empty();
        console.log($stuff.html());
        alert($stuff.html()); // Look behind, #stuff is empty.
        $stuff.html(ajaxContent);
        console.log($stuff.html());
    });
});

http://jsfiddle.net/62uSU/1

Another demonstration:

var $stuff = $('#stuff'),
    ajaxContent = $stuff.html(),
    $ajaxContent,
    colors = ['blue','green','red'],
    color = 0;

$stuff.on('click', '.button', function(){
    $.get('/echo/html/', function(){
        color++;
        if (color == colors.length) color = 0;
        console.log($stuff.html());
        alert($stuff.html());
        $ajaxContent = $(ajaxContent);
        $stuff.append($ajaxContent).css('color', colors[color]);
        console.log($stuff.html());
    });
});

http://jsfiddle.net/62uSU/2/

Kamilahkamillah answered 18/2, 2012 at 21:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.