why is <input type=“number” maxlength=“3”> not working in Safari?

后端 未结 8 1395
刺人心
刺人心 2020-12-09 01:55

I like to have an input with maximum 3 characters. In Firefox everything works fine I can only write 3 numbers inside the input - but in safari you can write a lot of number

相关标签:
8条回答
  • 2020-12-09 02:09

    I've accomplished it with:

    <input class="required" id="field" type="text" maxlength="3" pattern="([0-9]|[0-9]|[0-9])" name="cvv"/>
    

    and then in JavaScript I prevented the letters:

    $("#myField").keyup(function() {
        $("#myField").val(this.value.match(/[0-9]*/));
    });
    
    0 讨论(0)
  • 2020-12-09 02:09

    I used something very similar to @Jules answer except his won't allow the use of keys like shift+home. Since we're validating numbers I just used isNaN in the keyup function.

    $("#myField").keyup(function() {
        var e = $("#myField");
        if(isNaN(e.val())){
            e.val(e.val().match(/[0-9]*/));
        }
    });
    

    With...

    <input id="#myField" inputmode="numeric" maxlength="3" pattern="([0-9]{3})" type="text" />
    
    0 讨论(0)
  • 2020-12-09 02:11

    Using onKeyDown length can be restricted

    <input type="number" onKeyDown="if(this.value.length==10 && event.keyCode!=8) return false;">
    

    Happy Coding :)

    0 讨论(0)
  • 2020-12-09 02:14

    Basically Max and Min properties are not supported in Safari browser yet. I can see no flaw in the syntax. Are u using the Safari version 1.3+? or below that? Because maxlength property is supported from safari 1.3+.

    0 讨论(0)
  • 2020-12-09 02:16

    Here is a more simple solution. For me it worked

    <input type="number" id="cvv">
    
    
    $("#cvv").on("keypress", function(evt) {
      var keycode = evt.charCode || evt.keyCode;
      if (keycode == 46 || this.value.length==3) {
        return false;
      }
    });
    

    the JS block will prevent the "."(dot) so one cant enter float. We are keeping the input type as number so it will be only number as input. If the value length is 3 then it will return false, so input length also restricted.

    0 讨论(0)
  • 2020-12-09 02:17

    https://jsfiddle.net/zxqy609v/8/

    function fixMaxlength(inputNumber) {
      var maxlength = $(inputNumber).attr("maxlength");
        $(inputNumber).keyup(function (evt) {
        this.value = this.value.substring(0, maxlength);
        this.value = this.value.replace(/\D/g, '');
      });
    }
    
    0 讨论(0)
提交回复
热议问题