Reputation: 4368
I'm currently developing a small comment system with ajax. I want to unbind the keypress event when the enter key is pressed (to avoid duplicate comments) and rebind it after a successful ajax-call.
jQuery(".commentDiv textarea").keypress(function(event) {
if(event.which == 13 && !event.shiftKey) {
event.preventDefault();
var textarea = jQuery(this);
var comment = jQuery.trim(textarea.val());
if (!comment.length) {
alert("No valid comment.");
return false;
}
var the_data =
{
...
};
textarea.attr( "disabled", "disabled" );
textarea.val("Saving comment. Please wait...");
textarea.off('keypress.disabled');
// or textarea.unbind('keypress'); which also works
jQuery.post(ajaxurl, the_data, function(sp_response) {
textarea.attr( "disabled", false);
textarea.val("");
textarea.on('keypress.disabled', false); // not working
});
}
});
keypress.disabled
code is taken from How to bind, unbind and rebind (click) events in JQuery.
What is the easiest way to rebind the keypress event to the element?
Upvotes: 0
Views: 1868
Reputation: 148130
Instead of binding and unbind simply use a flag to skip un-wanted execution. Set the variable value at the start of event and reset it on post callback to get ready for next event.
var isAlreadyPressed = false;
jQuery(".commentDiv textarea").keypress(function(event) {
if(isAlreadyPressed) return;
isAlreadyPressed = true;
...
...
jQuery.post(ajaxurl, the_data, function(sp_response) {
isAlreadyPressed = false;
//your code here
});
Upvotes: 2