Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted

Have a look here: Using regex with jQuery[^] and try to change the code to your needs.
 
Share this answer
 
JavaScript
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';
        }
    };
}



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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900