HTML text input allows only numeric input

2018-12-31 00:22发布

Is there a quick way to set an HTML text input (<input type=text />) to only allow numeric keystrokes (plus '.')?

30条回答
十年一品温如言
2楼-- · 2018-12-31 01:24

You can use pattern for this:

<input id="numbers" pattern="[0-9.]+" type="number">

Here you can see the complete mobile website interface tips.

查看更多
骚的不知所云
3楼-- · 2018-12-31 01:25

HTML5 supports regexes, so you could use this:

<input id="numbersOnly" pattern="[0-9.]+" type="text">

Warning: Some browsers don't support this yet.

查看更多
泪湿衣
4楼-- · 2018-12-31 01:25

Just an other variant with jQuery using

$(".numeric").keypress(function() {
    return (/\d/.test(String.fromCharCode(event.which) ))
});
查看更多
谁念西风独自凉
5楼-- · 2018-12-31 01:27

Here is a simple one which allows for exactly one decimal, but no more:

<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" />

查看更多
看淡一切
6楼-- · 2018-12-31 01:28

2 solutions:

Use a form validator (for example with jQuery validation plugin)

Do a check during the onblur (i.e. when the user leaves the field) event of the input field, with the regular expression:

<script type="text/javascript">
function testField(field) {
    var regExpr = new RegExp("^\d*\.?\d*$");
    if (!regExpr.test(field.value)) {
      // Case of error
      field.value = "";
    }
}

</script>

<input type="text" ... onblur="testField(this);"/>
查看更多
冷夜・残月
7楼-- · 2018-12-31 01:28

A short and sweet implementation using jQuery and replace() instead of looking at event.keyCode or event.which:

$('input.numeric').live('keyup', function(e) {
  $(this).val($(this).val().replace(/[^0-9]/g, ''));
});

Only small side effect that the typed letter appears momentarily and CTRL/CMD + A seems to behave a bit strange.

查看更多
登录 后发表回答