jQuery .on() running before value given - javascript

Why does .on() not get the value of the form input field (#forgot) before the keypress has happened.
$(document).ready(function() {
$(document).on('keypress', '#pass', function() {
var value = $.trim($('#pass').val());
alert(value);
if (!value.length) {
alert("Show");
$('#forgot').show();
} else {
alert("Hide");
$('#forgot').hide();
}
});
});
When I type in the first character the alert shows no input. The second character leads to the value being only the first character. The .on() function seems to run before the key press is registered? How can I fix this or is there an alternative function?

keypress event triggered when you press a key. It will not wait for the value to come. Try with keyup. keyup gets triggered when you a key is released after pressing, till that time the value is proccessed. -
$(document).on('keyup', '#pass', function() {
keypress
The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser.
keyup
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.

Simply change keypress to keyup:
$(document).ready(function() {
$(document).on('keyup', '#pass', function() {
var value = $.trim($('#pass').val());
console.log(value);
if (!value.length) {
console.log("Show");
$('#forgot').show();
} else {
console.log("Hide");
$('#forgot').hide();
}
});
});

You need the keyup event instead of the keypress.
So replace:
$(document).on('keypress', '#pass', function() {
With
$(document).on('keyup', '#pass', function() {

keypress event is triggered when the key is pressed before the key is up). So it won't get the complete value.
Use keyup
JSFIDDLE DEMO
HTML
<input id="pass">
JQUERY
$(document).ready(function() {
$(document).on('keyup', '#pass', function() {
var value = $.trim($('#pass').val());
alert(value);
if (!value.length) {
alert("Show");
$('#forgot').show();
} else {
alert("Hide");
$('#forgot').hide();
}
});
});

Related

JQuery to detect both ctrlKey and mouse click

I'm new to JQuery, so I don't know much of the logic. I'm using it to find out which index of textarea I clicked while holding the CtrlKey.
However how do I assign a function on a combination of onclick and a keyboard event.
//What I have tried:
//textarea is the object where I want to detect both ctrlKey and mouse click
$(textarea).keydown(function(event){
if(event.ctrlKey){
$(textarea).click(function(event){
console.log("catched")
})
}
})
The above method does work, however It does so thrice, i.e.the console.log occurs thrice, so is there a way to make this catch it once.
also it somehow also occurs when not pressing the ctrl key.
You can simply check the ctrlKey property of the mouse event:
$(function() {
$('textarea').on('click', function (e) {
if (e.ctrlKey) {
console.log('clicked with ctrl');
} else {
console.log('clicked without ctrl');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea>click me</textarea>
A couple of small mistakes here, but you had the right idea :)
First off, it doesn't really make sense to stack the event handlers the way you have done - I get what you're thinking logically but in reality JS doesn't work that way. What you've actually said is this:
"If the user presses a key down in this textarea, and if their control key is down, add an event listener to this textarea that detects for clicks, and logs catched to the console".
What you really want is this:
$("#txtarea").click((e)=>{
if (e.ctrlKey) {
console.log("Control + Click!");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="txtarea"></textarea>
The ctrlKey property is exposed to all events, not just the keypresses.
If it were not though, (say you wanted A + Click), you would have a keydown event which sets global variable aDown to true, a keyup event which sets the aDown variable to false, and a click event which has an if statement in it which only works if aDown is true. This is shown below:
let aDown = false;
$("#txtarea").keydown((e)=>{
aDown = e.originalEvent.code == "KeyA";
});
$("#txtarea").keyup((e)=>{
aDown = false;
});
$("#txtarea").click((e)=>{
if (aDown) {
console.log("A + Click!");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Focus the textbox, hold down "A", and then click.<br>
<textarea id="txtarea"></textarea>
Note: On macOS, control + click is a shortcut for right-clicking, so your code won't fire. Consider listening to the oncontextmenu event and dealing with it if you care about macOS support - or perhaps changing your shortcut scheme.
I'd recommend setting up a global variable which holds the status of your ctrl key.
var ctrlDown=false;
Instead of simply listening for a keydown event, listen for a keyup event as well and update ctrldown accordingly.
$(textarea).keydown(function(event) {
if (event.ctrlKey) {
ctrlDown = true;
}
});
$(textarea).keyup(function(event) {
if (event.ctrlKey) {
ctrlDown = false;
}
});
Now that you know that the ctrl key is actually pressed you can do a simple check like:
$(textarea).click(function(event) {
if (ctrlDown) {
console.log("catched")
}
});

keypress handler canceling the event

I have the following code
jQuery('#parent').on('keypress', '.textbox', function(e) {
var btn = jQuery(this).closest('tr').find('.btn');
if (btn.length) {
btn.triggerHandler('click');
}
});
This code is a delegated keypress handler which is listening to the event of textboxes having class value ".textbox".
The handler finds the button with class ".btn" & calls its click handler which has an ajax call in it.
Problem is this seems to prevent the event from completing i.e if the value in box is "2" & I type in a "3",the handler executes but the value in the box remains to be "2" instead of a "23".
It works normal when I comment out the btn triggerHandler statement.
Ideas why this is happening?
Use keyup instead of keypress. As in your script you have triggered another event.
jQuery('#parent').on('keyup', '.textbox', function(e) {
var btn = jQuery(this).closest('tr').find('.btn');
if (btn.length) {
btn.triggerHandler('click');
}
});
keypress gets interrupted by triggerHandler and hence doesn't allow the default action of key press to occur. While keyup will perform default action first, then listen to handler.
I think you need to keyup function.
$(document).ready(function(){
$("input").keyup(function(){
var rs= $(this).val();
alert(rs);
$("input").css("background-color", "pink");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Enter your value: <input type="text">
Try to use 'onchange' insted of 'keypress' or 'keyup'
$(document).ready(function(){
$("input").onchange(function(){
var rs= $(this).val();
alert(rs);
$("input").css("background-color", "pink");
});
});

On keypress does not fire on the first key press

I have this method:
$(".txtB").on("keypress", function(event) {
console.log($(this).val());
if (...)
event.preventDefault();
});
But it works only after the second key pressed not for the first one. After that is triggered on every key press.
Anyone have an idea what could be?
Thanks.
Later edit:
It might be related to the way i use the function?
in HTML: onkeyup = "caseValuePercentageTwoDecimalRestriction()"
in JS:
function caseValuePercentageTwoDecimalRestriction() {
$(".caseValuePrecentageRestriction").on("keypress", function (event) {
...
??
The error is calling caseValuePercentageTwoDecimalRestriction on keyup event which is fired after keypress event.
keyup is called when you release the key while keypress is called when you press the key.
You should bind you keypress event handler on a document.ready event like this:
$(document).ready(function() {
$(".caseValuePrecentageRestriction").on("keypress", function (event) {
// do whatever you need
});
});
$(".txtB").keyup(function (event) {
console.log($(this).val());
});
To answer your question, Keypress event happens before the input change. But Keyup happens after the change. That's the only difference.
For input fields there is one more property input propertychange which works on change of text by keyboard as well as of you copy from mouse. Try using it
$(".txtB").on("input propertychange", function(event) {
console.log($(this).val());
if (...)
event.preventDefault();
});
use keyup instead of key press - Try:
$(".txtB").keyup(function (event) {
console.log($(this).val());
});
Then maybe .keydown would work for you?
Here we go:
Your code have to be like this:
$("input").keypress(function(){
$("span").text(i += 1);
alert("Test key pres");
});
<input type="text">
<p>Keypresses: <span>0</span></p>
Hope it helps;)
This will work for you but this is not perfect solution, it is just a work around:
$(document).ready(function(){
$(".txtB").on("keypress", function (event) {
console.log($(this).val() + event.key);
});
});
Here is a jsbin
As other users has shared Keypress event triggers before the value of textbox changed. You should use other events if you want updated value of textbox.
keypress events are fired before the new character is added to the input.
So the first keypress event is fired before the first character is added, while the input is still empty.
If you check this JSFIDDLE you will see an alert box even before you see value in input.
For example if you type a initially you will see an empty alert box, then type a different character, at that point you will see it is alerting a
You need to use either keyup or keydown. You can aslo use event.preventDefault() with keyup & keydown
try to use change instead of keypress or keyup because it will call first :
$(".txtB").change(function(event){
console.log($(this).val());
});

How do I determine the key that caused a textbox input event to fire?

If I have a textbox,
<input id='Sub' type='text'>
I can capture each time the input changes with:
sub = document.getElementById('Sub');
sub.addEventListener('input', function(e) {
// here the contents of the textbox is accessible via this.value
...
}, false);
I'd like to identify when backspace and delete are the causes of input firing so I can handle them specially. From what I can tell, neither e, nor this expose the key that was pressed to cause the input event to fire. Is there any way to find out what the key was?
"input" is not an event you want to capture. You have to catch "keypress" event. And then you can see "e.keyCode":
var sub = document.getElementById('Sub');
sub.addEventListener('keypress', function(e) {
console.log(e.keyCode)
}, false);
Here's a small demo: http://jsfiddle.net/9LZ9Z/

How to bind the enter/return key to user-defined function

I'm developing an application that runs on one page, and does not reload. I have a form with only an input type text, no submit button. I included the onchange event, after filling the textbox with data, I want to execute the function bound to the onchange event when I press enter, but the form is rather submitted and [it attempts to load a new page]. Please what do I do? Thanks
You can hook the keypress event on the text box and call your handler, and cancel the event to prevent the form submission:
$("selector_for_your_text_box").keypress(function(event) {
if (event.which === 13) {
// call your `change` logic here
// Cancel the event
return false;
}
});
Live example
This should work:
$(function() {
$('#yourInput').keypress(function(event) {
var key = event.keyCode || event.which;
if (key == 13) {
event.preventDefault();
// call your function here
});
});
Yuo can bind to the keypress event on the input:
$('#inputfieldid').keypress(function() {
alert('Handler for .keypress() called.');
});
Try the demo link http://jsfiddle.net/HDkJW/

Categories