skip to Main Content

I’m using input text field to input numbers only. I can’t use input type="number" because i probably use the decimal or (.) characters

Example of expected result:

  1. whole numbers
  2. numbers with decimal
  3. restricted alphabets

If possible, only decimal character are allowed, the rest will restricted also in special character.

3

Answers


  1. HTML

    In the attribute step , you can define your steps like .01.

    <input type="number" required name="price" min="0" value="0" step="any">
    

    jQuery

    In case you are looking for a regex that allows only numbers with an optional 2 decimal places

    HTML:

    <input name="my_field" pattern="^d*(.d{0,2})?$" />
    

    JS / jQuery:

    $(document).on('keydown', 'input[pattern]', function(e){
      var input = $(this);
      var oldVal = input.val();
      var regex = new RegExp(input.attr('pattern'), 'g');
    
      setTimeout(function(){
        var newVal = input.val();
        if(!regex.test(newVal)){
          input.val(oldVal); 
        }
      }, 1);
    });
    
    Login or Signup to reply.
  2. using jquery validation is easily possible for input

    Enter Input try it. <br/>
    <input type="text" onkeypress="return event.charCode >= 46 && event.charCode <= 57" onpaste="return false">
    Login or Signup to reply.
  3. Here you go. Regex check for input, allow only numeric value and decimal. And if condition check, it’s only take one decimal.

    Example:

    $(".decimal").on("input", function(evt) {
      var txt = $(this).val();
      txt = txt.replace(/[^0-9.]/g, '');
      if (txt.split('.').length > 2)
        txt = txt.replace(/.+$/, "");
      $(this).val(txt);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" name="numeric" class='decimal'>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search