Valentin Brasso
Valentin Brasso

Reputation: 1387

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").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?

Upvotes: 2

Views: 9296

Answers (6)

lincolnk
lincolnk

Reputation: 11238

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.

Upvotes: 1

Mic
Mic

Reputation: 25164

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:

  1. onfocus: a setInterval starts polling every 120ms or so, and checks the input for any change
  2. if there is a change do the relevant action
  3. onblur: a clearInterval stop the polling

Upvotes: 0

user356808
user356808

Reputation:

    $('.A, .B').keydown(function(event) { 
    if(!empty($('.A').val()) && !empty($('.B').val()))
        $(".C").attr("disabled","");
    else
        $(".C").removeAttr("disabled");
    });

Upvotes: 0

Anurag
Anurag

Reputation: 141879

Use the keyup event instead.

Upvotes: 2

Nimnam1
Nimnam1

Reputation: 513

have you tried using the keyUp event?

Upvotes: 6

Aaron Digulla
Aaron Digulla

Reputation: 328614

Attach your handler to the keyrelease event. The value should have been updated by then.

Upvotes: 1

Related Questions