KeyPress n KeyUp事件

编程入门 行业动态 更新时间:2024-10-22 09:26:30
本文介绍了KeyPress n KeyUp事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个文本字段,应该接受 只有数字 但我的条件很少, 1当我按第一个数字'M'时应该附加 2.当我按下更多数字时,'M'应该保持在最后。 例如。 1M 12M 123M 1236M 3.当我按下退格键时,应该删除M之前的数字并且不是M. i尝试使用按键事件检查仅限数字,它可以工作,但我认为我必须将它与keyup组合用于上述条件。

i have a text field which should accept only numbers but i have few conditions, 1. when i press first number 'M' should be appended 2. when i press further numbers 'M' should stay at end. eg. 1M 12M 123M 1236M 3. when i press backspace the number before M should be deleted and not M. i tried using keypress event check for number only,it works but i think i will have to combine it with keyup for the above conditions.

推荐答案

看看这里:在jQuery中使用正则表达式 [ ^ ]并尝试更改代码满足您的需求。 Have a look here: Using regex with jQuery[^] and try to change the code to your needs.

function fn() { var element = document.getElementById("NumberInput"); element.value = ""; element.onkeydown = function (e) { if (element.value.length == 0) { element.value = "M"; } }; element.onkeyup = function (e) { if (e.keyCode == 8) { var Number = element.value; var caretPos = element.selectionStart; if (caretPos == element.value.length) { Number = Number.replace('M', ''); Number = Number.substring(0, Number.length - 1); element.value = Number + 'M'; } } else { var Number = element.value; Number = Number.replace('M', ''); element.value = Number + 'M'; } }; }

在body onload上调用它。如果你熟悉jquery,你就可以做到这一点。这是针对您的问题的纯JavaScript解决方案。希望这会有所帮助。

call this on body onload. if you familiar with jquery you can do this less no of lines. this is pure javascript solution for your problem. hope this helps.

更多推荐

KeyPress n KeyUp事件

本文发布于:2023-11-11 07:05:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577722.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事件   KeyPress   KeyUp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!