I am running a script that will append an element upon selecting it from a dropdown list, that bit all works fine and appends the item. The item appended includes a button that will hide the appended item when clicked. What I can't seem to get to work is the hide function. The code seems to work fine if I put the element in manually into the HTML and click the hide button but for some reason when appending it it doesn't work?
$('#addteammember').click(function() {
var usernamevalue = $("#teammemberselected").val();
var teammemberfullname = $('#teammemberselected option:selected').text();
$('#teammemberlist').append("<li><input class='removeteam' type='button' value="+usernamevalue+" /><span class='listitem'>"+teammemberfullname+"</span></li>");
});
$('.removeteam').click(function () {
$(this).hide();
});
I am running a script that will append an element upon selecting it from a dropdown list, that bit all works fine and appends the item. The item appended includes a button that will hide the appended item when clicked. What I can't seem to get to work is the hide function. The code seems to work fine if I put the element in manually into the HTML and click the hide button but for some reason when appending it it doesn't work?
$('#addteammember').click(function() {
var usernamevalue = $("#teammemberselected").val();
var teammemberfullname = $('#teammemberselected option:selected').text();
$('#teammemberlist').append("<li><input class='removeteam' type='button' value="+usernamevalue+" /><span class='listitem'>"+teammemberfullname+"</span></li>");
});
$('.removeteam').click(function () {
$(this).hide();
});
Share
Improve this question
asked May 30, 2012 at 9:44
rmasperormaspero
6332 gold badges12 silver badges24 bronze badges
2 Answers
Reset to default 5It happens because you append the button dynamically but bind your click
handler for already existing elements only. You can use this code instead:
$("#teammemberlist").on("click", ".removeteam", function () {
$(this).hide();
});
Try live
function.
$(".removeteam").live("click", function() {
$(this).hide();
});