how to check if the value of a text input is empty right after the keypress event in javascript?
Here's the problem, in abstract terms: i have three input fields (A, B, C). two of them need to be text inputs (A and B), the third is of irrelevant type. I need to enable the third if A is not empty and B is not empty. I need to disable C if A is empty or B is empty.
The code
// empty is the empty function from the phpjs project // framework used: jQuery // A, B and C are classes here $(".A, .B").keypress(function(){ if( !empty($(".A").val()) && !empty($(".B开发者_StackOverflow").val()) ) $(".C").attr("disabled",""); else $(".C").removeAttr("disabled"); });
I want to be able to check this on keypress, but when requesting the value of the input that is edited when the keypress event occurs i get the value that was calculated before the keypress event.
Has anybody stumbled upon this before and solved it?
have you tried using the keyUp event?
Use the keyup
event instead.
Attach your handler to the keyrelease
event. The value should have been updated by then.
use a combination of handlers for keyup
and change
. the keyup
handler will update as the user types (excepting edge cases like holding a key down, which doesn't seem like a concern here) and the change
handler will catch things like the user cutting the text with mouse actions before they can switch to field C. as an added measure you could add verification on field C's focus
event, to make sure A and B really have something.
$('.A, .B').keydown(function(event) {
if(!empty($('.A').val()) && !empty($('.B').val()))
$(".C").attr("disabled","");
else
$(".C").removeAttr("disabled");
});
At the keypress
event, the value of the INPUT
is not yet set. Hence you can't easily know if it is empty.
While the keyup
fires, the value of the INPUT
is set.
But things get worse. The user can empty the field with the mouse or the Edit menu of the browser. In that case keyup
is not fired.
In our web app we auto-save the values.
Like in Mac OS, if you know, there is almost no save buttons.
To allow a reaction here is more or less what we do:
onfocus
: asetInterval
starts polling every 120ms or so, and checks the input for any change- if there is a change do the relevant action
onblur
: aclearInterval
stop the polling
精彩评论