How does onchange and onkeyup work in javascript? - javascript

I was trying to validate a password field when I found the javascript code on the net. Can someone please explain when is the "onchange" fired and why does the code not work when I replace onkeyup with onchange (last 2 lines in javascript code)
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
<div class="password" id="password-fields" style="display:none">
Password: <input type="password" name="password" class="password" id="password"><br>
Confirm Password: <input type="password" name="password" class="password" id="confirm-password">
</div>
<div> <input type="submit" name="submit"> </div>
</form>

The change event occurs when you leave an input field after having changed its value. It doesn't fire immediately as the user changes the value, only when they've finished, which is detected by them using the keyboard or mouse to select a different element on the page.
The keyup event occurs after every keystroke. This allows you to take action while the user is typing.

The onChange event occurs when the value is assigned to the field, which is usually when the field loses focus.
The onKey events are bound to the keypress, meaning, they are triggered by the key itself and not related to the value assignment of the field.
The onKeyUp event will only fire when the user physically stops pressing the key (when the key goes "up").
You can test the behavior here.

Related

jQuery Enter keyup function needs to be hit twice before function is called

I have an event listener that looks for the keyup of the enter key in an input box. There is also a button that is next to the submission box that the user can click which submits the data and triggers a function. On the keyup, I am directly calling the function.
The issue is that the function only works when I press enter the second time. Example: I enter a number and hit enter, the page goes into a loading modal like it should, but nothing gets displayed on the page. If I click on the input box again (not changing the number I inputted) and hit enter again, it goes into the loading modal and then it displays the charts that I have.
I am unsure on why it works the second time but not the first? I have seen multiple posts on pressing once triggering multiple function calls, but can't find anything that you need to do an event twice just to get one function call.
Here is the jQuery for enter key
document.getElementById('SN').addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
self.getInformation();
}
});
Here is the input box.
<div class="col-md-3">
<label class="control-label" for="SN">Serial Number</label>
<input class="form-control text-box single-line" id="SN" name="SN" type="number" data-bind="value: SN" />
</div>
Here is the button that works when the user actually clicks it instead of hitting enter in the input box.
<div class="col-md-offset-6 col-md-3 col-md-push-3">
<label></label>
<button id="getInformationBtn" class="btn btn-success btn-block" data-bind="click: getInformation">Get Information</button>
</div>

Mute HTML validation message while typing

Steps to reproduce the issue:
Set an input of type email / phone
Set the input as required
Hit form submit on the wrong pattern for email
The HTML validation message should be now visible.
Keep entering text into the input box
On entering the text in the input box after the validation message has been kicked in, the validation message persists and gets displayed on every keystroke.
I even tried setting setCustomValidity("") on keyup event but that does not help either.
Here is an example fiddle.
Here is a gif of the problem:
You can see that until I add #gmail.com to the email input, it keeps showing the HTML validation.
Any help would be appreciated.
Source code for the same.
HTML
<form>
<p>
<label for="t2">What's your e-mail?</label>
<input id="email" type="email" id="t2" name="email" required>
</p>
<p>
<button>Submit</button>
</p>
</form>
JS
$("#email").on("keyup", function (e) {
if (e.target.value.lenth !== 0) {
e.target.setCustomValidity("");
}
});
When the user presses enter and the input validation fails, that input fires an invalid event. So, you can add an invalid handler to customize (and possibly prevent) the resulting behavior. The invalid event does not get triggered by further inputs of normal characters, but the invalid pop-up will keep appearing as long as the input remains invalid and focused. When the input is unfocused (blurred), the validation pop-up will disappear. It will re-appear only after the user re-focuses the input and presses enter when the input text is still invalid.
So, one possible solution is to add an invalid listener that keeps track of whether the error pop-up is showing or not. Then, add a keydown listener that checks if the pop-up is showing. If the pop-up is showing, blur and then focus the element, so as to make the pop-up disappear until the next time the user presses enter:
let errorShowing = false;
$("#email")
.on('invalid', (e) => {
errorShowing = true;
})
.on("keydown", function(e) {
if (!errorShowing) return;
setTimeout(() => {
this.blur();
this.focus();
});
errorShowing = false;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<label for="t2">What's your e-mail?</label>
<input id="email" type="email" id="t2" name="email" required>
</form>

Changing focus from one input to the next with a barcode scanner

I am using a barcode scanner to enter data into input fields on a webpage. I set up the form and autofocus on the first input field. When the first barcode is entered into the first input field I would like focus to jump to the next input field. However, as soon as I enter the first barcode the form 'submits'. Here is the html I am using:
<form id="barcode1" name="barcode" method="Post" action="#">
<div>
<label for="S1">Barcode 1 </label>
<input id="S1" class="bcode" type="text" name="S1" autofocus/>
<label for="S2">Barcode 2 </label>
<input id="S2" class="bcode" type="text" name="S2" />
<label for="S3">Barcode 3 </label>
<input id="S3" class="bcode" type="text" name="S3" />
</div>
<p><input type="submit" name="Submit" value="Submit"></p>
</form>
I have tried solutions from similar SO questions here and [here] (http://jsfiddle.net/davidThomas/ZmAEG/), but they don't seem to work.
Ideally I would like to have a solution something like this (the second link above), so please let me know where or why this is not working and what I can do to fix it.
$('form').on('keypress','input',function(e){
var eClassName = this.className,
index = $(this).index('.' + eClassName) + 1;
if (e.which === 13){
e.preventDefault();
$('input.' + eClassName)
.eq(index)
.focus();
}
});
You need to return false in order to prevent the enter key from submitting the form.
The answer to this question will help you: Prevent form submission with enter key
//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
if ( e.which == 13 ) // Enter key = keycode 13
{
$(this).next().focus(); //Use whatever selector necessary to focus the 'next' input
return false;
}
});
No need to make any changes to your bar scanner.
If your barcode scanner is a keyboard wedge, you should be able to configure the trailing character to a TAB.
It seems like, by default, your scanner is trailing with an ENTER (carriage return).
Another option would be to also check for a LF (decimal 10) in your javascript code.
Looks like your function will never get called because browser submits the form on Enter. You may have to suppress submit until all fields are filled (or some other condition) by intercepting submit event first.
$( "form" ).submit(function( event ) {
if(/*all req. fields are filled -> submit the form*/)
$(this).submit();
event.preventDefault();
});

OnKeyPress ENTER Reloads The Page

<input type="text" onkeypress="if (event.keyCode==13){ func_name(this.value);}" id="userinput"/>
I have a textfield where i have called a function on hitting the ENTER key.The problem is that the page gets reloaded while it should not have been so as i am calling only a js function.Please tell me what am i doing wrong.
The form is being submitted by the pressing of enter. You can attach an onsubmit event to the form, and return false to prevent submission (and true to submit). YOu can use this feature to validate the data before submitting, or to intercept your keypress event.
Alternatively, as commented on below, you can use event.preventDefault() to prevent the pressing of enter triggering a submit.
Something like this...
<form action=".">
<input type="text" onkeypress="console.log('happy days'); event.preventDefault()">
</form>
I know this is an old message, but I solved it adding "return false":
<input type="text" onkeypress="if (event.keyCode==13){ func_name(this.value);return false;}" id="userinput"/>
Maybe it is usefull to other with a similar issue.

Putting focus on a textbox in onchange event

I am trying to get it so that when a certain value is put into a textbox, the focus will stay on the textbox(and an alert will be shown in production). I am trying to get this to work in Firefox 3.5.7 with no luck.
How can I make it so when a textbox is a certain value at onchange that it will stay focused/refocus on the textbox?
Live example is at http://jsbin.com/ipina
<body>
Enter your name: <input type="text" name="fname" id="fname" onchange="
if(this.value=='foo'){
this.select();
this.focus();
}
" />
</body>
Also, I don't get any javascript errors or warnings in the Error Console on executing this code.
When the onchange event is fired, the user is focused on the textbox.
Maybe you might want to use the blur event to re-focus on the textbox if the value is 'foo'.
If you need instantaneous results, you should use onkeyup.
<body>
Enter your name: <input type="text" name="fname" id="fname" onkeyup="
if(this.value=='foo'){
this.select();
this.focus();
}
" />
</body>
According to Javascript onchange different in IE and FireFox I needed to set the focus after the onchange event occurs, so I had to end up with something like this:
Enter your name: <input type="text" name="fname" id="fname" onblur="
if(this.value=='foo'){
alert('bah');
setTimeout('document.getElementById(\'fname\').focus();document.getElementById(\'fname\').select();',0);
}
" />
And also I had to catch it when the focus was lost, not necessarily when the text was changed, so I had to use onblur instead of onchange.
Live: http://jsbin.com/ofeva

Categories

Resources