简体   繁体   English

输入值,包含最小和最大数字

[英]Input value with a min and max number

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. 下面是一个输入数字表单,使用JavaScript,我添加了一些代码行,其中可写入的最小数量为1,要写入的最大数量为50.并且当有人尝试键入小于1的任何数字时它将自动替换为1或50,但我没有成功实现这一点,我需要你的帮助。

  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"> 

There's already a HTML attribute pair for this exact purpose - min and max : 为此目的已经有一个HTML属性对 - minmax

 <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)>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM