views:

39

answers:

2

Hi Guys,

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?

+1  A: 

Try using event.currentTarget, where event is the first param of your function.

See here: http://api.jquery.com/event.currentTarget

Fiona Holder
returns same thing as (this)... (HtmlInputElement). i think im getting the right thing, just dont know how to get the value from the keypress event.
RPM1984
+1  A: 

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);
  });
});
Bang Dao
Yep, that was it. Thanks!
RPM1984