简体   繁体   English

在将按键事件应用于 DOM 之前,如何确定按键事件之后的值是什么?

[英]How can I determine what a value would be after a keypress event BEFORE it is applied to the DOM?

I have a textbox which a user will be typing a number into.我有一个文本框,用户将在其中输入一个数字。 I want to limit that number to a max of 5 million (5000000).我想将该数字限制为最多 500 万(5000000)。 I want to prohibit any keypresses which would cause that number to go above 5 million.我想禁止任何会导致该数字超过 500 万的按键。 I know I could wait for keyup and use the value then, but I want to prevent the keypress entirely.我知道我可以等待 keyup 并使用该值,但我想完全阻止按键。

How can I determine what the value of the textbox would be after a given keydown/keypress event is applied BEFORE it actually happens?在实际发生之前应用给定的 keydown/keypress 事件之后,如何确定文本框的值是多少?

Edit: To make it clear, consider this scenario:编辑:为了清楚起见,请考虑以下情况:

The box currently contains the number "4000000".该框当前包含数字“4000000”。

The user highlights the last number and changes it to a 1, so that it becomes "4000001"用户突出显示最后一个数字并将其更改为 1,使其变为“4000001”

But the user COULD have simply added a 1 to the end.但是用户可以简单地在末尾添加一个 1。 The keydown event would look exactly the same, but the result would be outside the range of values I want to allow. keydown 事件看起来完全相同,但结果将超出我想要允许的值范围。

I need to know what the value of the box would be if the keydown event were applied normally, but I need to know before it happens.如果 keydown 事件正常应用,我需要知道框的值是多少,但我需要在它发生之前知道。

To be clear, this post is NOT about limiting a text field to numbers-only.需要明确的是,这篇文章不是关于将文本字段限制为仅限数字。 I'm capable of doing that.我有能力做到这一点。

Is that what you looking for?这就是你要找的吗?

 var max = 4000000; var last_value; $('#someinput').on('input', function(e){ var value = $(this).val(); if(value<=max) last_value = value; else $(this).val(last_value); })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="someinput" type="number"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM