jQuery .keyPress() - 如何获取触发事件的输入值? [英] jQuery .keyPress() - How to get value of input which triggered event?

查看:812
本文介绍了jQuery .keyPress() - 如何获取触发事件的输入值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图做一些jQuery验证(没有插件 - 请不要回答只使用validate-js插件)。

我正在配置一个客户端事件处理程序按键为doc中每个必填字段准备:

  $(document).ready(function(){
$('#myform input.required')。each(function(){
$(this).keypress(onRequiredFieldKeyPress);
});
});

正确地触发每个按键上的这个事件:

 函数onRequiredFieldKeyPress(){
if($(this).val()。trim()==''){
$(this)。接下来( '时间')HTML( '*')显示()。 // show req field indicator
} else {
$(this).next('em')。html('*')。hide(); //隐藏req字段指示符


code


但$(this) .val()始终为空/空。看起来它正在传递一个HTMLInputElement,这正是我所期望的,但它几乎就像我需要项目这到其他jQuery类型?



基本上我正在尝试这样做:在我已经连线的任何字段的keypress事件上(它们都是输入元素),调用该函数。在该函数中,如果该字段的值为''(空),则显示一个隐藏字段,显示一个必填字段指示符。



我并不在乎哪个实际元素触发了按键,因为我的逻辑行为将是相同的。我只需要得到实际的价值。



我是否缺少某些东西?

解决方案

因为您正在使用按键事件。按键有三个阶段:

1.按键:按键时按

2.按住:按键

3。 Key:释放键

在你的情况下,问题可以通过使用keyup事件来解决


  $(document).ready(function(){
$('#myform input.required')。each(function(){
$(this).keyup(onRequiredFieldKeyPress);
});
});


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?

解决方案

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

这篇关于jQuery .keyPress() - 如何获取触发事件的输入值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆