最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Input value with a min and max number - Stack Overflow

programmeradmin2浏览0评论

Below is an input number form and with JavaScript, I have added some line of codes with the minimum number that can be written is 1 and the maximum number to be written would be 50. And when someone would try to type any number less than 1 and greater than 50 it would automatically replace it with number 1 or 50 but I'm not having success achieving this and I need your help.

    document.getElementById('info1').addEventListener("input", function () {
    let num = +this.value, max = 50, min = 1;
    if (num > max || num < min) {
        return false;
      }
})
<input type="number" id="info1" size="4">

Below is an input number form and with JavaScript, I have added some line of codes with the minimum number that can be written is 1 and the maximum number to be written would be 50. And when someone would try to type any number less than 1 and greater than 50 it would automatically replace it with number 1 or 50 but I'm not having success achieving this and I need your help.

    document.getElementById('info1').addEventListener("input", function () {
    let num = +this.value, max = 50, min = 1;
    if (num > max || num < min) {
        return false;
      }
})
<input type="number" id="info1" size="4">

Share Improve this question edited Jun 22, 2019 at 21:29 Jack Bashford 44.1k11 gold badges55 silver badges82 bronze badges asked Jun 22, 2019 at 21:01 BeharBehar 1791 gold badge3 silver badges14 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 9

There's already a HTML attribute pair for this exact purpose - min and max:

<input type="number" min="1" max="50">

If you also want this to occur when a user enters a number outside of the range:

document.getElementById("inp").addEventListener("change", function() {
  let v = parseInt(this.value);
  if (v < 1) this.value = 1;
  if (v > 50) this.value = 50;
});
<input type="number" min="1" max="50" id="inp">

function imposeMinMax(el){
  if(el.value != ""){
    if(parseInt(el.value) < parseInt(el.min)){
      el.value = el.min;
    }
    if(parseInt(el.value) > parseInt(el.max)){
      el.value = el.max;
    }
  }
}

<input type=number min=1 max=50 onkeyup=imposeMinMax(this)>
发布评论

评论列表(0)

  1. 暂无评论