Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Selecting dynamically created elements and pushing to Firebase

Beginner to all of this, playing around with Firebase. Basically, I want to retrieve text entries from Firebase and have an "Approve" button next to it. When the button is clicked, I want that specific text entry to be pushed to a new Firebase location and the text removed from the page. I am creating the button and the text dynamically and I am having some trouble with selecting the button and the divs I created. I know I have to use on() but I'm unsure of how to use it.

Thanks!

approveRef.on('child_added', function(snapshot) {
 var posts = snapshot.val();
 $('<div id="post">').text(posts.text).append('<button style ="button" id="approve">Approve</button>').appendTo($('#feed'));
});

$('#approve').on("click", function(){
    var text = $('#post').val();
    postsRef.push({'text':text});
    $('#post').remove();

});
like image 867
Sam Avatar asked Jul 10 '13 01:07

Sam


2 Answers

You have to bind .on() on a container of your dynamically added element that is already on the page when you load it, and have it like this:

$('#yourContainer').on('click', '#approve', function(){
    //your code here..
});
like image 156
Nikko Reyes Avatar answered Oct 05 '22 23:10

Nikko Reyes


Your .on() didn't work, because you are adding the button dynamically. You can't find the dynamically added elements directly using that elements id selector like $('#approve'). So you should bind .on() with $(document) selector. This will always contain your dynamically added elements.

$(document).on( eventName, selector, function(){} );

$(document).on('click','#approve',function(){
//your code here
});
like image 21
Keerthi Avatar answered Oct 06 '22 00:10

Keerthi