Search code examples
jquerykeypressdigits

jquery replace character when keypress


I'm searching to make an input with default value 0.00

When you try to write a number let say 6, in input to appear 0.06 next 62, to appear 0.62 ... Maximum 3 digits separated by dot after first digit ...

I saw something like this on Phone IMEI check, but I don't remember where ... 13 digits 0 and when you write a digit it replace last one with new digit

I didn't know how to search something like this ...

Thanks and sorry if it's a stupid question.

Stefan


Solution

  • I hope this will solve your problem. I have used event.key on keyup event to determine which key is pressed and then processed the input data shows the result.

    var result = 0;
    $(document).ready(function() {
      $("input").keyup(function(event) {
        var k = event.key;
        if (!isNaN(k)) { //check if input is a number
          if((parseFloat(result)) < 1) { //condition to keep result in maximum of 3 digit
            result = parseFloat(result*1000) + parseFloat(k);
            result /= 100;
            result = result.toFixed(2); //Convert into a string, keeping only two decimals
            $("input").val(result);
          } else {
            $("input").val(result);
          }
        } else if (k == "Backspace" || k == "Delete") { //check if backspace or delete is pressed
          result = 0;
          $("input").val("0.00");
        } else { //check if any non-numeric key pressed
          $("input").val(parseFloat(result).toFixed(2));// assures that always shows formatted result
        }
      });
    });
    <!DOCTYPE html>
    <html>
    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    </head>
    <body>
      Enter number:
      <input type="text" placeholder="0.00" autofocus>
    </body>
    </html>