jquery 获取某个值得键名_jQuery .keyPress() - 如何获取触发事件的输入值?

这篇博客讨论了在不使用验证插件的情况下,使用 jQuery 进行客户端验证的问题。作者遇到的问题是在 keypress 事件处理函数中,$(this).val() 总是返回空值。解决方案是改用 keyup 事件来正确获取输入元素的值。通过监听 keyup 事件,当释放按键时,可以正确检查输入字段是否为空,并据此显示或隐藏必填字段指示器。
摘要由CSDN通过智能技术生成

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

});

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值