How to allow numbers, backspace, delete, left and right arrow keys in the html text?

前端 未结 5 2035
野趣味
野趣味 2021-02-05 06:25

I am using following javascript code which I think should only allow numbers, backspace, delet, left arrow and right arrow keys in textbox, but it is also allowing alphabets. I

相关标签:
5条回答
  • 2021-02-05 07:05

    No doubt your code is correct but you missed "return" keyword in textbox.

    <input type="text" onkeypress='return validateQty(event);'>
    

    You can see the code here

    0 讨论(0)
  • 2021-02-05 07:06
    <input type="text"  class="form-control" id="dompetku_msisdn" name="dompetku_msisdn" placeholder="Phone Number"  aria-describedby="helpBlock" onkeydown='return (event.which >= 48 && event.which <= 57) || event.which == 8 || event.which == 46 || event.which == 37 || event.which == 39' required /> </input>
    
    0 讨论(0)
  • 2021-02-05 07:06

          function isNumberKey(evt)
          {
             var charCode = (evt.which) ? evt.which : event.keyCode
             if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;
             return true;
          }
    <HTML>
       <HEAD>
       </HEAD>
       <BODY>
          <input id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar" maxlength="10">
       </BODY>
    </HTML>

    0 讨论(0)
  • 2021-02-05 07:19

    I modified his code a bit, so you can just add a class to an input

    $(".numberonly").keydown(function(e){
        // Number Only
        if (e.keyCode == 8 || e.keyCode == 46
           || e.keyCode == 37 || e.keyCode == 39) {
              return true;
          }
          else if ( e.keyCode < 48 || e.keyCode > 57 ) {
            e.preventDefault();
          }
      });
    

    add class to an input

    <input type="text" class="numberonly" />
    
    0 讨论(0)
  • 2021-02-05 07:20
    const validateQty = (event) => {
        var key = window.event ? event.keyCode : event.which;
        console.log(event);
        if (event.keyCode === 8 || event.keyCode === 46
            || event.keyCode === 37 || event.keyCode === 39) {
            return true;
        } else if (key < 48 || key > 57) {
            return false;
        } else { return true; }
    };
    
    
    <input type="text" onkeydown='return validateQty(event);'>
    
    0 讨论(0)
提交回复
热议问题