Disable Text Entry in <input type=“number”>

前端 未结 2 1594
别跟我提以往
别跟我提以往 2020-12-16 03:55

I am making a simple web app. At one part of it, I have included an input box of type=\"number\"


An

相关标签:
2条回答
  • 2020-12-16 03:59

    You can use HTML5 input type number to restrict only number entries:

    <input type="number" name="someid" />
    

    This will work only in HTML5 complaint browser. Make sure your html document's doctype is:

    <!DOCTYPE html>
    

    For general purpose, you can have JS validation as below:

    function isNumberKey(evt){
        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    }
    
    <input type="someid" name="number" onkeypress="return isNumberKey(event)"/>
    

    If you want to allow decimals replace the "if condition" with this:

    if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))
    

    Source: HTML Text Input allow only Numeric input

    0 讨论(0)
  • 2020-12-16 04:16

    You can use JavaScript (e.g. with jQuery) to allow only specific characters:

    // Catch all events related to changes
    $('#textbox').on('change keyup', function() {
      // Remove invalid characters
      var sanitized = $(this).val().replace(/[^0-9]/g, '');
      // Update value
      $(this).val(sanitized);
    });
    

    Here is a fiddle.

    Same thing with support for floats:

    // Catch all events related to changes
    $('#textbox').on('change keyup', function() {
      // Remove invalid characters
      var sanitized = $(this).val().replace(/[^0-9.]/g, '');
      // Remove the first point if there is more than one
      sanitized = sanitized.replace(/\.(?=.*\.)/, '');
      // Update value
      $(this).val(sanitized);
    });
    

    And here is another fiddle.

    Update: Although you might not need this, here is a solution that allows a leading minus sign.

    // Catch all events related to changes
    $('#textbox').on('change keyup', function() {
      // Remove invalid characters
      var sanitized = $(this).val().replace(/[^-0-9]/g, '');
      // Remove non-leading minus signs
      sanitized = sanitized.replace(/(.)-+/g, '$1');
      // Update value
      $(this).val(sanitized);
    });
    

    3rd fiddle

    And now a final solution that allows only valid decimals (including floats and negative numbers):

    // Catch all events related to changes
    $('#textbox').on('change keyup', function() {
      // Remove invalid characters
      var sanitized = $(this).val().replace(/[^-.0-9]/g, '');
      // Remove non-leading minus signs
      sanitized = sanitized.replace(/(.)-+/g, '$1');
      // Remove the first point if there is more than one
      sanitized = sanitized.replace(/\.(?=.*\.)/g, '');
      // Update value
      $(this).val(sanitized);
    });
    

    Final fiddle

    0 讨论(0)
提交回复
热议问题