Reputation: 2282
Very new to jQuery, if dupe question sorry at this point not even sure I am using correct verbiage.
I need to add a li item to a ul based on a click event of a ListBox (user selects text and a new li is added with the selected text). And I need to add a icon, label and input on the li item. The icon needs to be a 'remove' icon.
How can I wire up the function to remove the newly added li item via jQuery?
Here is what I have tried;
$(function() {
function addSelectedWordCriteria() {
var selectedWord = $("#wsWords").val();
$("#wsCriteriaList").append("<li><a href='#' class='wsCriteriaRemove'><span class='ui-icon ui-icon-circle-close'/></a><em class='wsFilteredWord'>" + selectedWord + "</em><input type='textbox' maxlength='200' class='wsFilteredWords'/></li>");
$("#wsCriteriaList a:last").bind("click", "removeSelectedWordCriteria");
};
function removeSelectedWordCriteria() {
$("#wsCriteriaList").selected().remove();
}
})
<%= Html.ListBox("wsWords", ViewData["Words"] as IEnumerable<SelectListItem>) %>
<ul id="wsCriteriaList">
</ul>
Thanks for any suggestions.
Upvotes: 0
Views: 987
Reputation: 21630
You're not using the bind method properly - you have your method call enclosed in quotes.
http://docs.jquery.com/Events/bind#typedatafn
Upvotes: 0
Reputation: 828200
The problem is that is you bind the click event with bind("click", "removeSelectedWordCriteria")
you are using the data parameter of the bind function.
When the user clicks the button nothing will happen, because the callback function is not defined.
You should pass directly the function reference or create an anonymous function as the handler:
$("#wsCriteriaList a").bind('click', removeSelectedWordCriteria);
Or
$("#wsCriteriaList a").click(removeSelectedWordCriteria);
Or
$("#wsCriteriaList a").click(function(){removeSelectedWordCriteria();});
Upvotes: 0
Reputation: 9110
To your immediate question, since the click event gives you a reference to the element that sent the event, you could use it quickly determine what should be removed:
function removeSelectedWordCriteria() {
$(this).parent().remove();
}
Other things I may change about this code:
As ScottE pointed out, this could be a great place to use the new live function. Outside of your addSelectedWordCriteria method, you should be able to put in:
$("#wsCriteriaList a").live("click", "removeSelectedWordCriteria");
And that will register all of your a tags with the same event even as they get added.
Let me know if you have additional questions.
Upvotes: 1