why is <input type=“number” maxlength=“3”> n

2020-02-03 09:34发布

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 numbers inside.

You can test it in both browsers with this: http://flowplayer.org/tools/demos/validator/custom-validators.htm

For now I realized it with a validate plugin - but just for interest I like to know why isn’t this working?

EDIT:

with this it's working

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

answer: How can I prevent letters inside a text element?

7条回答
淡お忘
2楼-- · 2020-02-03 09:42

You may try to user type="text" and oninput as below. This will let the numbers only.

<input type="text" maxlength="3" oninput="this.value=this.value.replace(/[^0-9]/g,'');" id="myId"/>
查看更多
祖国的老花朵
3楼-- · 2020-02-03 09:45

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.

查看更多
beautiful°
4楼-- · 2020-02-03 09:50

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]*/));
});
查看更多
The star\"
5楼-- · 2020-02-03 09:50

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" />
查看更多
我想做一个坏孩纸
6楼-- · 2020-02-03 09:57

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, '');
  });
}
查看更多
女痞
7楼-- · 2020-02-03 10:00

Using onKeyDown length can be restricted

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

Happy Coding :)

查看更多
登录 后发表回答