How do I undelegate the #submit click event?
$(document).ready(function(){
$(".agent img").click(function(){
$(".agent-form").remove();
var agentid = $(this).attr("alt"),
response = "<form method='post' action='' class='agent-form'><textarea placeholder='Your Comment' name='comment' id='comment'></textarea><input type='button' value='submit' id='submit' /></form>";
$(response).hide().appendTo(this.parentNode).fadeIn();
$(".agent").delegate("#submit","click",function(){
var message = $("#comment").val();
message = escape(message);
var dataString = "agent="+agentid+"&message="+message;
$.ajax({
type: "POST",
url: "includes/newcomment.asp",
data: dataString,
success: function(){
console.log(dataString);
}
});
});
});
});
I want to undelegate all #submit click events that were created on previous .agent img clicks. The problem is that if the user clicks on an agent img then decides to click on another img the ajax submits to different datastrings.
Per the jQuery doc for
.delegate(), you can use.undelegate()to remove an event handlers.You don’t show us your HTML, but this sounds more like you should just have one delegated event handler that is always there rather than creating one, removing one, creating another, etc… You can store the agentid in the form element when you create it and then retrieve it upon the submit handler like this.