我有一个文本字段,应该接受 只有数字 但我的条件很少, 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事件
发布评论