Does 'keypress' jQuery event fire before an inputs value is updated? - javascript

I have a keypress event listener on an input field to confirm a password. I want the button on the page to be disabled until the password and confirm-password fields have matching values. I am using the .keypress() jQuery function, but it seems to always be one character behind what I expect it to be?
Here is the code
$('#confirm').keypress(function() {
console.log('#confirm').val();
if($('#password').val() == $('#confirm').val()) {
$('button').removeProp('disabled');
console.log("yes");
} else {
console.log("no");
}
});
But when I inspect element and look at the console window on my page, the first time the event is fired it prints the form value as blank. Then when I enter a second character, it prints only the first, and when I type a third character it prints the first two, etc.
For example, if I put asd into the password field and begin typing the same into the confirm field the output will look like this:
<blank>
no
a
no
as
no
So at this point both password and confirm fields have "asd", but I need to enter an extra character before that is recognized and the "disabled" property is removed from the button.
I have tried using .change() instead of .keypress() but that doesn't fire until the input field loses focus, which is not what I want.

I want the button on the page to be disabled until the password and confirm-password fields have matching values
If this is your goal, you can add event listeners to both inputs that call a validation function:
$('#password').on("input", function() { validatePassword(); });
$('#confirm').on("input", function() { validatePassword(); });
function validatePassword() {
if($('#password').val() && $('#confirm').val() && $('#password').val() == $('#confirm').val()) {
$('button').prop('disabled', false);
} else {
$('button').prop('disabled', true);
}
}
It also may be worthwhile adding an ID to the button. Using 'button' would enable/disable all elements on the page.
Example: https://jsfiddle.net/doL4t9vv/1/

I had the same problem few months ago.
Try to use the keyup function from Jquery.
Keypress event is fired when you press the key, so the input is not fill yet.
Keyup event is fired when you release the key.

Can use input event and simplify this down to
var $passwords =$('#confirm, #password').on('input', function() {
var thisValue = this.value.trim();
// does this input have value and does it match other
var isValid = thisValue && thisValue === $passwords.not(this).val().trim();
// boolean used for disabled property
$('button').prop('disabled', !isValid);
});

Related

Type and focus out event in jquery?

I have written a blur() event to handle focus out event on a text field. The code looks like this.
$("input[type=text]").blur(function (event) {
if(this.value){
//do something
}
event.originalEvent.handled = true;
});
I have a situation where a text-field is automatically getting focus with the text from previous page.
To give an example, in flipkart.com, type some text in the search field and click search. My event handler must execute for focus out event. (It is happening correctly).
In the next page, the text entered is prepopulated in the text-field and focus is also on it. So in this page, if I do some action, the text-field will lose focus and the same event gets called again. I don't need this to happen.
Is there a way to avoid this? By combining two event handlers? Please help.
Change your code so that the function is only bound to the element after a user explicitly interacts with the element like so:
$("input[type=text]").on('keyup keypress change click', function() {
$("input[type=text]").blur(function(event) {
if (this.value) {
//do something
alert('blur was called after interacting with element');
}
event.originalEvent.handled = true;
});
});
$('#test').focus();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" value="some value">
Try this : You know the text value from previous page, just compare it with current text value, if both same then don't do any action. See below code
$(function(){
var prevTextValue = "read your previous text value here";
$("input[type=text]").blur(function (event) {
//check if value is not empty and not equal to previous value
if(this.value!="" && this.value != prevTextValue){
//do something
}
event.originalEvent.handled = true;
});
});

Triggering a jQuery custom event in a separate div when user starts typing in a text input

I am trying to get a separate div (a custom 'continue' button) to appear when the user starts typing into a text input.
I am currently using this:
var submitButton = $('#submitButton');
submitButton.hide();
submitButton.on("showSubmitButton", function(event) {
$( this ).show();
$( this ).css('opacity', '0');
$( this ).fadeTo(400, 0.6);
});
var textInput = $('#textInput');
textInput.click(function() {
$( this ).find('input:text').val(''); // this clears the default 'type your name here' text
});
textInput.keyDown(function() {
submitButton.trigger("showSubmitButton");
});
When I had the "showSubmitButton" line inside the textInput.click function the submit button appeared on the click, but I want the button only to appear when the user has typed something into the input.
I have also used .keyPress(), but both key events trigger a 'has no method' error. I assume I must be using them incorrectly, but I don't know how.
The shorthand functions for event handlers aren't camel case, so it's .keydown(), .keypress(), etc. rather than .keyDown() or .keyPress(). That said, I'd use either the input or keypress events (depending on browser support), with a check to see if the value of the textbox isn't an empty string:
textInput.find('input:text').on('input', function(e) {
if($.trim(this.value).length > 0) {
submitButton.trigger('showSubmitButton');
}
else {
// consider hiding the submit button?
}
});
It is not keyDown - it is keydown

Running check on empty input type of text

How would I run a check after a keypress function to see if an inputs value was empty so I can do another action.
For example.
$("input[name=amount]").keypress(function() {
$("table[name=apply]").show();
});
I want to hide the table if the user deletes all the keystrokes.
$("input[name=amount]").keyup(function() {
if (this.value == '') {
$("table[name=apply]").hide();
} else {
$("table[name=apply]").show();
}
});
You will probably want to use either the keyup or change event so the value of the text-box has changed before the event handler runs. The keypress event fires before the value of the input has changed, so for instance if the input is blank and a key is entered, the value in the event handler would still read as blank.
Here is a demo: http://jsfiddle.net/jasper/C5KPq/
Use the keyup() method to perform the check after the keystroke has finished:
$("input[name=amount]").keyup(function() {
if(this.value === ''){....}
});
If you bind to the keypress or keydown events, the value of the input inside your event handler will not yet have been affected by the keystroke. This is why you need to bind to keyup instead.
You can try this using keyup event instead of keypress because keypress will not give you the latest value.
$("input[name=amount]").keyup(function() {
//Here this points to the textbox element and value gives its content
if(this.value == ''){
$("table[name=apply]").show();
}
});
If you want to toggle the table the you can use this.
$("input[name=amount]").keyup(function() {
$("table[name=apply]").toggle(this.value != '');
});
toggle(showOrHide) - Display or hide the matched elements.
Demo
you can use the following
if( $(this).val() == "")
try:
if ($("input[name=amount]").val() == '') // input is empty

Jquery : how to trigger an event when the user clear a textbox

i have a function that currently working on .keypress event when the user right something in the textbox it do some code, but i want the same event to be triggered also when the user clear the textbox .change doesn't help since it fires after the user change the focus to something else
Thanks
The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)
$("#inputname").keyup(function() {
if (!this.value) {
alert('The box is empty');
}
});
jsFiddle
As Josh says, this gets fired for every character code that is pressed in the input. This is mostly just showing that you need to use the keyup event to trigger backspace, rather than the keypress event you are currently using.
The solution by Jonathon Bolster does not cover all cases. I adapted it to also cover modifications by cutting and pasting:
$("#inputname").on('change keyup copy paste cut', function() {
//!this.value ...
});
see http://jsfiddle.net/gonfidentschal/XxLq2/
Unfortunately it's not possible to catch the cases where the field's value is set using javascript. If you set the value yourself it's not an issue because you know when you do it... but when you're using a library such as AngularJS that updates the view when the state changes then it can be a bit more work. Or you have to use a timer to check the value.
Also see the answer for Detecting input change in jQuery? which suggests the 'input' event understood by modern browsers. So just:
$("#inputname").on('input', function() {
//!this.value ...
});
Another way that does this in a concise manner is listening for "input" event on textarea/input-type:text fields
/**
* Listens on textarea input.
* Considers: undo, cut, paste, backspc, keyboard input, etc
*/
$("#myContainer").on("input", "textarea", function() {
if (!this.value) {
}
});
You can check the value of the input field inside the on input' function() and combine it with an if/else statement and it will work very well as in the code below :
$( "#myinputid" ).on('input', function() {
if($(this).val() != "") {
//Do action here like in this example am hiding the previous table row
$(this).closest("tr").prev("tr").hide(); //hides previous row
}else{
$(this).closest("tr").prev("tr").show(); //shows previous row
}
});
Inside your .keypress or .keyup function, check to see if the value of the input is empty. For example:
$("#some-input").keyup(function(){
if($(this).val() == "") {
// input is cleared
}
});
<input type="text" id="some-input" />

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

Categories

Resources