Disable writing in input type number HTML5

后端 未结 5 1203
青春惊慌失措
青春惊慌失措 2020-12-16 14:57

I want to disable writing into a field of type number, for avoiding strings data, and write just numbers, so how to enable scroll bars only ?

相关标签:
5条回答
  • 2020-12-16 15:21

    Firstly, your markup is incorrect. The form tags must surround the input tag:

    <form name="my_form">
        <input ...code...
        <input ...code...
    </form>
    

    Secondly, if you are using HTML5 and want a number input, you can use this:

    <input type="number" name="my_number" min="0" max="100" step="1" value="50"/>
    

    (from W3Schools)

    Be aware that current browser implementations of the "number" input vary.

    You then reference the value using Javascript, or have it posted using the form.

    0 讨论(0)
  • 2020-12-16 15:22

    You can cancel KeyDown event using this

    <input type="number" onKeyDown="return false">

    0 讨论(0)
  • 2020-12-16 15:22

    No Scrolling, no increment of numbers, max-length provided, no copy paste.

    Check out the Fiddle below, which has the features needed within a type number form field.

    HTML

    <form class="form-horizontal home" role="form" action="" method="post" id="payment-form" novalidate="novalidate">
    <label for="number">Mobile number : </label>
    <input class="form-control" id="number" name="number" type="number" data-rule-required="true" aria-required="true" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" onKeyDown="if(this.value.length==10 && event.keyCode!=8) return false;">
    </form>
    

    CSS

    input[type=number]::-webkit-inner-spin-button, 
    input[type=number]::-webkit-outer-spin-button { 
      -webkit-appearance: none; 
      margin: 0; 
    }
    

    DEMO - JSFIDDLE

    0 讨论(0)
  • 2020-12-16 15:25

    If I understood you correctly, I just implemented the same thing myself using vanilla Javascript (no jQuery).

    window.onload = () => {
      //add event listener to prevent the default behavior
      const mouseOnlyNumberInputField = document.getElementById("mouse-only-number-input");
      mouseOnlyNumberInputField.addEventListener("keypress", (event) => {
        event.preventDefault();
      });
    }
    <form>
      <input id="mouse-only-number-input" name="number" type="number" min="1" max="20" value="10" />
    </form>

    0 讨论(0)
  • 2020-12-16 15:35

    If you are able/allowed to use jQuery, you can disable keypress on the type='number'.

    $("[type='number']").keypress(function (evt) {
        evt.preventDefault();
    });
    

    This allows you to use up and down arrows on the input, but doesn't allow keyboard input.

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