I have the following code to count and trigger some functions using jQuery:
jQuery('#input_guideName').keyup(function(e)
{
if(this.value.length == 5)
{
jQuery("#guide_btnCreateGuide").css({'background-position':'top', 'cursor':'pointer'});
jQuery("#guide_btnCreateGuide").bind('click', function() {
createNewGuide();
});
}
else if(this.value.length < 5)
{
jQuery("#guide_btnCreateGuide").css({'background-position':'bottom', 'cursor':'default'});
jQuery("#guide_btnCreateGuide").unbind('click');
}
});
Here are some issues I have encountered:
-
Using CTRL + V is counted as 2 keyup, and the code will run twice, executing the
createNewGuide()twice. How can I avoid this? -
Pasting code using right mouse button is not detected. How can I detect this? Bu putting a listener on RightMouseButton?
-
If I paste text > 5 characters, none of my functions are triggered. I cannot add a control on
if(this.value.length > 5), because thencreateNewGuide();will fire for each keyup.
Any ideas how I can overcome these issues?
EDIT
My “operational objective” is to create a new guide in DB and the guide name must be at least 5 characters long. The button for the ‘create guide’ will not be clickable unless name is at least 5 characters long.
Handling Ctrl + V isn’t as bad as you might think but handling paste in general is. There’s no
onpasteevent (at least not cross browser) and the middle/right click paste actually happens AFTER themouseupevent so if you just did.bind('change keyup mouseup', func...you’d miss it. Given all that, I think a timeout is the best way to do this:Even in your original code,
createNewGuide()wasn’t being called on each keyup withthis.value > 5but rather you were registering a new event on each keyup that call createNewGuide, so then on click, it would get called multiple times.By doing
unbindbeforebindprevents duplicate functions getting registered onclick, so you won’t ever callcreateNewGuide()twice, even on ctrl + v;You can tune the delay if you’re worried about your users hitting the button quickly after shorting the input.