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 or change() event to do username verification?
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.
Related
When using jquery .change on an input the event will only be fired when the input loses focus
In my case, I need to make a call to the service (check if value is valid) as soon as the input value is changed. How could I accomplish this?
UPDATED for clarification and example
examples: http://jsfiddle.net/pxfunc/5kpeJ/
Method 1. input event
In modern browsers use the input event. This event will fire when the user is typing into a text field, pasting, undoing, basically anytime the value changed from one value to another.
In jQuery do that like this
$('#someInput').bind('input', function() {
$(this).val() // get the current value of the input field.
});
starting with jQuery 1.7, replace bind with on:
$('#someInput').on('input', function() {
$(this).val() // get the current value of the input field.
});
Method 2. keyup event
For older browsers use the keyup event (this will fire once a key on the keyboard has been released, this event can give a sort of false positive because when "w" is released the input value is changed and the keyup event fires, but also when the "shift" key is released the keyup event fires but no change has been made to the input.). Also this method doesn't fire if the user right-clicks and pastes from the context menu:
$('#someInput').keyup(function() {
$(this).val() // get the current value of the input field.
});
Method 3. Timer (setInterval or setTimeout)
To get around the limitations of keyup you can set a timer to periodically check the value of the input to determine a change in value. You can use setInterval or setTimeout to do this timer check. See the marked answer on this SO question: jQuery textbox change event or see the fiddle for a working example using focus and blur events to start and stop the timer for a specific input field
If you've got HTML5:
oninput (fires only when a change actually happens, but does so immediately)
Otherwise you need to check for all these events which might indicate a change to the input element's value:
onchange
onkeyup (not keydown or keypress as the input's value won't have the new keystroke in it yet)
onpaste (when supported)
and maybe:
onmouseup (I'm not sure about this one)
With HTML5 and without using jQuery, you can using the input event:
var input = document.querySelector('input');
input.addEventListener('input', function()
{
console.log('input changed to: ', input.value);
});
This will fire each time the input's text changes.
Supported in IE9+ and other browsers.
Try it live in a jsFiddle here.
As others already suggested, the solution in your case is to sniff multiple events.
Plugins doing this job often listen for the following events:
$input.on('change keydown keypress keyup mousedown click mouseup', handler);
If you think it may fit, you can add focus, blur and other events too.
I suggest not to exceed in the events to listen, as it loads in the browser memory further procedures to execute according to the user's behaviour.
Attention: note that changing the value of an input element with JavaScript (e.g. through the jQuery .val() method) won't fire any of the events above.
(Reference: https://api.jquery.com/change/).
// .blur is triggered when element loses focus
$('#target').blur(function() {
alert($(this).val());
});
// To trigger manually use:
$('#target').blur();
If you want the event to be fired whenever something is changed within the element then you could use the keyup event.
There are jQuery events like keyup and keypress which you can use with input HTML Elements.
You could additionally use the blur() event.
This covers every change to an input using jQuery 1.7 and above:
$(".inputElement").on("input", null, null, callbackFunction);
I have
<input type="text" id="pies" value="" />
and
$( document ).ready(function() {
$('#pies').on('change', function() { alert('cham'); });
$('#pies').focus();
$('#pies').val('kooooo');
$('#pies').blur();
});
Why browser doesn't fire change event? How can I make that browser will fire change event. I don't want to trigger "change" manually, because if I will trigger change, in some cases trigger change will be triggered twice. This is only example.
Call the change using :
$('#pies').change();
You have to do it manually
$('#pies').change();
As docs says
The change event is sent to an element when its value changes. This event is limited to elements, boxes and 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.
In auto complete case try to do $("#pies").trigger("autocompleteselect");
Better use keypress instead of change
My OnChange event does not work properly - I want to trigger a function when user changes a textbox's value. But in my tests I have seen that the function triggers when textbox's value changes and textbox loses focus. Something wrong with my browser? Or is it about the ability of JavaScript? If the last one is true how can I can do that? Thanks in advance.
onchange event will trigger when an input field loses focus or when an option is selected from a dropdown menu, that's normal behavior.
If you want an event that will be triggered as the user types in an input field, you can use onkeypress, onkeydown or onkeyup events.
You could do with jquery:
$("textbox_id").keyup(function(){
//do something here
});
write the jquery code on keyup event and blur event also, because if user paste some copied data into textbox by using mouse only in that case only blur event called by jquery.
want to create a password field where I want to check for capsLock on/off on keystroke. Once a user enters a value in smallcase and try to another field want to validate the password value. Thus want to use onkeypress for every key pressed and then onblur at the end.
But the problem I am facing is every time onkeypress is checked onblur is also executed.
<input type="password" size=50 id='r5PswFld' name="name" value="" onkeypress="checkCapsLock(event)" onblur=chkPsw(this.id) >
can anyone help me how to attain this.
thanks in advance...
better if I am able to do this using only javascript/html/css I me no other technologies like jquery...
This event is getting fired because you in checking the other checkbox input, you are blurring focus away from the current control.
Attach the onblur at the start your checkCapsLock(event) :
document.getElementById("r5PswFld").onblur = function(chkPsw(this.id)'){};
If you find yourself having to perform an action that will focus away, detach it:
document.getElementById("r5PswFld").onblur = function(){};
Next time you fire checkCapsLock it will reacttach if you need to. You could then also remove the onblue attribute completely from your code.
That said, be careful of any onblur validation. If is obtrusive (like an alert) then it could quickly get very frustrating for the user.
EDIT
In repose to the comment below, I thought I'd correct for the problem of other blur bindings. I'll use jQuery for preference.
The correct solution would look something like:
function MyBlurFunc(){
chkPsw(this.id);
}
To bind:
$("#r5PswFld").blur(MyBlurFunc);
To unbind
$("#r5PswFld").unbind('blur', MyBlurFunc);
Unfortunately, onblur will get called whenever focus is left from the field, meaning if you open some sort of message box informing the user of having capslock on, you're removing focus and thus trigger the onblur event.
An alternative might be to activate a flag which you assign to be true prior to opening a message box so that in the case in which you enter chkPsw, you can ignore it.
In other words:
var flgEventsOff = false;
function checkCapsLock(event) {
if (fieldValueIsUpper) {
flgEventsOff = true;
alert('Please turn off capslock!');
flgEventsOff = false;
}
}
function chkPsw(id) {
if(!flgEventsOff) {
// Validate password
}
}
No, the blur event won't be executed the same time a keyPress event is fired. I assume you have an alert() statement within your checkCapsLock() event handler, which causes the loss of focus.
Why would you not just change it to lowecase on the onblur event before it validates?
I'd like to invoke default keydown event handler from javascript. Is it possible?
If the event has an explicit event handler you can just invoke it directly:
// Precondition - the element has an explicit handler registered
element.onkeydown();
Otherwise, there's no way to explicitly tell the browser to do "what it would have done anyway". The only way to get this to happen is to not stop the event from bubbling - which can be a real pain if you want to set a timeout and then allow the event to continue, it's essentially not possible.
In most cases, though, you can invoke your own code on an event handler and let the keyDown event continue to the browser. And if this isn't possibel for whatever reason, you can usually write your own method that will simulate the effects of the event (e.g. change the content of an input field, submit the form, etc.)
There is no default keydown event. The keydown event occurs when the key is pressed on any form elements, followed immediately by the keypress event, and possibly the textInput event on text box when you enter a value. Then the keyup event is generated when the key is released
The following example shows the use of the onKeyDown event handler to display a message in the text box.
<body><form action="" method="POST" id="myForm"><input type="text" name="myText" onKeyDown="changeVal()"><script type="text/javascript" language="JavaScript">s1 = new String(myForm.myText.value)function changeVal() { s1 = "You pressed a key"
myForm.myText.value = s1.toUpperCase() }</script></form></body>