Alex Reynolds
Alex Reynolds

Reputation: 96927

How do I use jquery to validate an input field on change?

I have an input field:

<input type="text" name="notifyEmail" id="parametersEmail" value="" size=40 />

I have a chunk of jquery code that works when I hit tab or otherwise leave the field, which calls a validation routine:

$("#parametersEmail").blur(function(event) {
    validateParameterEmail();
});

What I would like to do is run the validateParameterEmail() function whenever the value or content of the input field changes.

So I then also tried the .change() handler:

$("#parametersEmail").change(function(event) {
    validateParameterEmail();
});

But when I change the contents of parametersEmail, this handler does not call the validation function.

Is there another handler I should be using, instead? Or can I not attach multiple event handlers to the input field?

Upvotes: 9

Views: 36022

Answers (4)

FlameStorm
FlameStorm

Reputation: 1004

( Reality on almost 2017-th year )

The best way is to set once the callback on all need events about input value changing.

There are:

  • keyup : user typed something in the input
  • change : common known method about stored changes in input
  • click : some inputs take changes by mouse too
  • paste : Yea! Ctrl+V, Crtl+Ins, RightMouseButton+Paste can change input value too
  • propertychange : when some JS changes our input at any way, this event will fired
  • input : new standard's event that supports all modern browsers, use it too

So, we can set all of them once:

$("#parametersEmail").bind("propertychange change click keyup input paste", function(event) {
    validateParameterEmail();
});

Hope this helps for someone. ;)

Upvotes: 4

Victor
Victor

Reputation: 4721

Try this:

$("#parametersEmail").bind('blur', function(event) {} );

and

$("#parametersEmail").bind('keyup', function(event) {} );

Upvotes: 6

benhowdle89
benhowdle89

Reputation: 37464

Change refers to when you click away/move from the input. You may be looking for onKeyUp().

Upvotes: 0

Ish
Ish

Reputation: 29536

Try $("#parametersEmail").keydown(function(event) {})

Upvotes: 9

Related Questions