username html field
Username: <input type="text" name="username" id="username" />
keyup() event
$(document).ready(function(){ $('#username').on('keyup', function(){ var username = $("#username").val(); alert(username); }); });
change() event
$(document).ready(function(){ $("#username").change(function() { var username = $("#username").val(); alert(username); }); });
My question is should I use
keyup()
event orchange()
event to do username verification?
2 Answers
They are almost the same thing. In jQuery or JavaScript, I would have to recommend the change()
event. The reason you should not use keyup()
is because if a user inputs a value using autofill, it will not fire the keyup()
event. However, autofill does fire the change()
event, and your verification script will run, and the input will be verified.
NOTE: Normally, change()
is fired when the element loses focus. If you want to check data after every key press, you could combine keyup()
and change()
, which would allow you to parse the data on both events. This is the best of both worlds in my opinion.
Hope this helps!
Use keyup with debouncing, it's more user friendly.
keyup
Whenever you release a key.
The keyup event is sent to an element when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type. -- http://api.jquery.com/change/
change
Whenever the content of that field changes, generally, it happens when you remove focus from that field, but not only that.
The change event is sent to an element when its value changes. This event is limited to input
elements, textarea
boxes and select
elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus. -- http://api.jquery.com/change/
Use keyup and a debounced callback So that you verification process isn't fired after each key stroke, but only if the user stops typing, check this example: http://codepen.io/desandro/full/JDugF, open the page, open the javascript console, and start scrolling.