jQuery keyup event lagging on user input - javascript

I have a textbox where a user can only enter numeric data. I'm using the following function on keyup of the textbox:
$('#ssn').keyup(function () {
var val = this.value.replace(/\D/g, '');
this.value = val;
});
The problem I'm running into is the lag when the user keys up on a restricted key, the character displays for a moment before it's replaced with the empty string. And holding down a key will display a stream of characters in the box until the key is released. Is there a way to prevent this behavior? I've tried different keyboard events like keydown or keypress and they didn't seem to behave any better.
Here is a fiddle of the problem: https://jsfiddle.net/oxpy96g9/

Converting my comment to an answer
Rather than listening to the keyup event, listen to the input event so that the event is fired when the value changes rather than when the key is released:
Updated Example
$('#numbers').on('input', function() {
this.value = this.value.replace(/\D/g, '');
});

Related

Trigger Keypress event of a input field on keypress of another input field?

I have two input fields i want to trigger keypress of one input field on keypress of another input field.
What i have tried is
$('#example').keypress(function(event) {
var press = jQuery.Event("keypress");
var code = event.keyCode || event.which;
press.which = code ;
$('#search').trigger(press);
});
both example and search are input fields. Why i am doing so i because when i enter text in simple field it has to enter text in another field which filters search results.
Try this :
JavaScript
$('#example').on('keypress keyup keydown',function(event) {
// create the event
var press = jQuery.Event(event.type);
var code = event.keyCode || event.which;
press.which = code ;
// trigger
$('#search').val(this.value);
$('#search').trigger(event.type, {'event': press});
});
// Omit - Check if search box reacts
$('#search').on('keypress keyup keydown',function(event) {
// sample
console.log(event.type);
});
Demo here : http://jsbin.com/pebac/1/edit
Note that even if you successfully manage to trigger a keypress event this doesn't act as a real one, meaning that the char won't be appended to the input.
Guess it's like $.click()
$('#search').keypress();
If all you want to do is to copy the content of one field to the other, I'd say it's better to do $('#search').val($(this).val()); instead of triggering the keypress event on #search.

getting new value of input field on keypressed

i have an input field where i allow users to insert an integer.
Now when ever they insert a value into the input field i check with ajax if it is higher than a specefic amount for this purpose i need to get the "new" value of the input field
i have tried the following:
$('.wanted_amount').keydown(function () {
var value = $(this).val();
}
however this returns ""
Meaning that it doesnt register the value untill after keydown
So how i can i get the new value of the input field with javascript?
can you please try this,
$(function(){
$('.wanted_amount').keyup(function () {
var value = $(this).val(); // alert(value);
});
});
keydown is event, which helps to trigger event when detects a finger on a key
keyup is event, which helps to trigger event when the key is released
You have not closed function properly.
keydown() will be triggered when key is pressed and keyup() will be triggered after pressing the key. In your case, keyup() is more suitable.
Try this:
$('.wanted_amount').keyup(function () {
var value = $(this).val();
console.log(value);
});
Fiddle here.

Need to assign an event listener to the tab key using keycodes in JavaScript?

I have currently an eventlistener listening for when a user enters an email address in a textbox on an html website. It then displays an alert when it detects an email address is being entered. Currently I have set it up whereby it detects the event blur then checks whether it meets the regex then an alert will display. This creates many alerts and is not very accurate as the alert
I need the eventlistener to listen for when the tab key specifically is pressed. I know I need to use KeyCodes but have not used them before. This eventlistener is currently working dynamically as it is a Firefox AddOn that scans a webpage so the eventlistener is not specifically attached to a specific input box.
Code:
vrs_getWin.document.getElementsByTagName("body")[0].innerHTML = bodyContents;
var inputFields = vrs_getWin.document.getElementsByTagName("input");
for(inputC=0; inputC < inputFields.length; inputC++) {
var elementT = inputFields[inputC].getAttribute("id");
inputFields[inputC].addEventListener("blur", function(){
var emailPattern = /(\w[-._\w]*\w#\w[-._\w]*\w\.\w{2,3})/g;
var resultEmail = emailPattern.test(vrs_getWin.document.getElementById(elementT).value);
if(result) {
prompts.alert(null, "Test", vrs_getWin.document.getElementById(elementT).value);
}
}, false);
}
Any help with this will be much appreciated.
I think from a UX stand point, I would not recommend using a javascript alert to notify the user of a problem, especially if you want the notification to happen when they have completed a single form input. The blur event would be my recommendation, and use some other visual cue to notify the user.
But, if you want to go with the tab key, the event your looking for is 'keydown', or 'keyup'. To use it you listen for the keydown event then check if the event.keyCode == '9'. (tab key)
document.addEventListener('keydown', function(e){
if( e.keyCode == '9' ){
alert('You pressed the tab key.');
}
}, false);
To get the keycodes of keys I like to pop open a console and type in:
document.addEventListener('keydown', function(e){
console.log( e.keyCode );
}, false);
Then when you press a key, it will output the keycode for that key.

jQuery .keyPress() - How to get value of input which triggered event?

Trying to do some jQuery validation (without the plugin - please no answers like "Just use the validate-js plugin").
I'm wiring up a client-side event handler keypress for each "required field" on doc ready:
$(document).ready(function() {
$('#myform input.required').each(function() {
$(this).keypress(onRequiredFieldKeyPress);
});
});
Which correctly fires this event on each keypress:
function onRequiredFieldKeyPress() {
if ($(this).val().trim() == '') {
$(this).next('em').html('*').show(); // show req field indicator
} else {
$(this).next('em').html('*').hide(); // hide req field indicator
}
}
But $(this).val() is always null/empty. Looks like it's passing in an "HTMLInputElement" which is what i'd expect, but it's almost like i have to project this into some other jQuery type?
Essentially i'm trying to do this: on the keypress event of any field which i have wired-up (which are all input elements), call that function. In that function, if that field has a value of '' (empty), then show a hidden field which displays a required field indicator.
I don't really care which actual element fired the keypress, as the behaviour of my logic will be the same. I just need to get the actual value.
Am i missing something?
Because you are using key-press event. Key press has 3 phase:
1. Key down: when key is press
2. Key hold: key is hold down
3. Key up: key is release
In your case, problem can be solved by using keyup event
$(document).ready(function() {
$('#myform input.required').each(function() {
$(this).keyup(onRequiredFieldKeyPress);
});
});
Try using event.currentTarget, where event is the first param of your function.
See here: http://api.jquery.com/event.currentTarget

How do I grab the value from an html form input box as its being entered?

How do I grab the value from an input box as its being entered?
onkeyup will be triggered every time a key is released. While it looks to be the solution it has some problems.
If the user move the cursor with the arrows, it is triggered and you have to check yourself if the field value didn't change.
If the user copy/paste a value in the input field with the mouse, or click undo/redo in the browser, onkeyup is not triggered.
Like in a mac or in google docs, I didn't want a save button to submit forms in our app, here is how I do it.
Any comment, or shortcut is welcome as it is a bit heavy.
onfocus, store the current value of the field, and start an interval to check for changes
when the user moves something in the input, there is a comparison with the old value, if different a save is triggered
onblur, when the user moves away from the field, clear the interval and event handlers
Here is the function I use, elm is the input field reference and after is a callback function called when the value is changed:
<html>
<head>
<title>so</title>
</head>
<body>
<input type="text" onfocus="changeField(this, fldChanged);">
<script>
function changeField(elm, after){
var old, to, val,
chk = function(){
val = elm.value;
if(!old && val === elm.defaultValue){
old = val;
}else if(old !== val){
old = val;
after(elm);
}
};
chk();
to = setInterval(chk, 400);
elm.onblur = function(){
to && clearInterval(to);
elm.onblur = null;
};
};
function fldChanged(elm){
console.log('changed to:' + elm.value);
}
</script>
</body>
</html>
use an onchange event handler for the input box.
http://www.htmlcodetutorial.com/forms/_INPUT_onChange.html
I noticed you used the "jquery" tag. For jQuery, you can use the .keypress() method.
From the API documentation:
Description: Bind an event handler to the "keypress" JavaScript
event, or trigger that event on an
element.
The event will fire every time keyboard input is registered by the browser.
.keydown() and .keyup() are also available. Their behavior is slightly different from .keypress() and is outlined by the API documentation as well.
The nice thing about jQuery is that you can use the same code across Firefox, IE, Safari, Opera and Chrome.

Categories

Resources