HTML文本框上的Keydown事件问题 [英] Keydown event issue on HTML textbox

查看:276
本文介绍了HTML文本框上的Keydown事件问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受年份的字段,所以我创建了

I have a field that accepts the year, so I have created

input type="number" 

并实施 keydown事件以限制用户输入超过4位数字。

and implemented keydown event to restrict user to enter more than 4 digits.

现在我遇到了一个问题,需要帮助来弄清楚逻辑。以下是这种情况:

Now I'm facing an issue and need help in figuring out the logic. Following is the case:


  • 在文本框中输入4位数

  • 使用SHIFT +选择输入的文本箭头键

现在,如果你键入一个数字,它应该替换数据,但由于我已禁止它,它不会。需要覆盖这种情况。

Now if you type a number it should replace the data but since I have barred it, it will not. Need to cover this case.

还可以在以下 JSFiddle中找到代码

我在输入[type = number] 上也有很多css和验证,所以无法更改为输入[type = text]

I also have lot of css and validation on input[type=number], so cannot change to input[type=text].

此外,在移动设备上使用相同的表单,当用户使用时选择文本框,应该出现数字键盘。

Also same form is used on mobile devices, and when user selects textbox, numeric keyboard should appear.

搜索选项时,我发现 JSfiddle 可以指导我们走向正确的方向。
此处的问题还是输入[type = number] 不支持选择属性。 参考

while searching for option, I found a JSfiddle that could direct us to right direction. Issue here also is input[type=number] does not support selection property. Reference

作为替代方案,我们决定转移到输入[type = tel] 。这将以类似的方式工作,但将允许我们使用maxLength属性。如果有人有更好的方法,请分享。

As an alternative, we have decided to move to input[type=tel]. This would work in similar fashion, but will allow us to use maxLength attribute. Still if anyone has a better way, please share.

推荐答案

HTML:

<input type="tel" class="year" maxlength="4" data-temp="">

jQuery:

$(document).on('input', '.year', function(){
    var txt = $(this).val();
    if(isNaN(txt) || txt > 9999){
        $(this).val( $(this).data('temp') );
        return;
    }
    $(this).data('temp', txt);
});

JSFiddle

这篇关于HTML文本框上的Keydown事件问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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