On my page there are ht开发者_JAVA技巧ml inputs (type = text) that I'm binding to with jQuery. When the user presses the enter key or leaves the textbox after changing a value, I want to submit it (using ajax).
I created an "enter" event since jQuery doesn't supply one. I actually got it from a post here. It looks like this:
$(document.body).delegate(":input","keyup",function(e){
if(e.which == 13)
$(this).trigger("enter");
});
And my binding is done like so (any class that has 'submit-on-enter-or-on-change'):
$('.submit-on-enter-or-on-change').bind("enter change",function(){
submitValue(this);
)};
The problem is when the user presses the 'enter' key and the value has changed, submitValue(this)
gets called twice!
Is there any way to prevent this? One submit at a time is enough for me :)
Would something like this work?
var submitted = false;
$('.submit-on-enter-or-on-change').bind("enter change",function(){
if (submitted) return;
submitted = true;
submitValue(this);
)};
One workaround would be to debounce the submitValue call.
The optional third parameter of the bind()
method is a boolean that (when false) stops the event from bubbling (thus the handler from getting invoked twice). Is that what you need?
More info: http://api.jquery.com/bind/
Okay, the fix to my issue was to simply remove the "enter" binding and just use "change".
Apparently, IE doesn't accept the 'enter' key on a change when using it inline with html, but it DOES work when you bind via jQuery.
i.e
<input type="text" onchange="submitValue(this)" />
doesn't submit on enter key.
精彩评论