jQuery .keyPress() - How to get value of input which triggered event?

只谈情不闲聊 提交于 2020-01-13 10:08:08

问题


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:


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);
  });
});



回答2:


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

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



来源:https://stackoverflow.com/questions/3437893/jquery-keypress-how-to-get-value-of-input-which-triggered-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!