Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  82] [ 4]  / answers: 1 / hits: 31566  / 13 Years ago, wed, february 22, 2012, 12:00:00

I have this simple HTML code:



<div id=new_gallery>
<p id=add_gallery>Add new gallery</p>
</div>


and jQuery code:



<script>
$(#add_gallery).click(function() {
$(#new_gallery).append('<input namenew_gallery /><a href=# id=create_new_gallery>Add</a>');
$(this).remove();
});

$(#create_new_gallery).on('click', function(){
alert('1');
});
</script>


First function is working, but second one is not. I need to create new input element, send data via ajax, and then delete the input element and append a p element once again. How can I do this?


More From » jquery

 Answers
20

When the second statement runs, the element #create_new_gallery does not exist yet so it does nothing.



You can do the binding to the click event after you created the element for instance, this ensures the element exists in the DOM:



$(#add_gallery).click(function() {
$(#new_gallery).append('<input name=new_gallery /><a href=# id=create_new_gallery>Add</a>');
$(this).remove();
$(#create_new_gallery).on('click', function() {
alert('1');
});
});​


DEMO






Here is a little bit more optimized version. It's a bit non-sense to append an element and have to re-query for it (event though querying by id is the fastest method. Besides, it's best to use the chaining capabilities of jQuery afterall:



$(#add_gallery).click(function() {
var $gallery = $(#new_gallery);

$('<input name=new_gallery />').appendTo($gallery);
$('<a href=# id=create_new_gallery>Add</a>')
.on('click', function() {
alert('1');
})
.appendTo($gallery);

$(this).remove();
});​


DEMO


[#87302] Monday, February 20, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marcelofrankiea

Total Points: 200
Total Questions: 96
Total Answers: 101

Location: Tonga
Member since Tue, Nov 30, 2021
3 Years ago
;