纯javascript检测数字输入值的变化 [英] pure javascript detect change in number typed input value

查看:70
本文介绍了纯javascript检测数字输入值的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

< pre class = snippet-code-js lang-js prettyprint-override> window.onload = function init(){console.log( DOM就绪!); var输入,值;输入= document.getElementById( yourGuess);输入= input.value; input.addEventListener( checking,check,false);检查(值); }功能检查(值){if(输入< 0&&输入> 10){alert(数字必须在0-10之间);值= 0; }}

 < label for = yourGuess>您选择:< / label><输入id = yourGuess type = number min = 0 max = 10>  



我在任何地方都找不到与上述问题相对应的解决方案。



因此,我有一个数字类型输入,并声明了一个分别为0和10的min和max属性。



用户可以单击输入字段并在其外部更改其值范围,因此我需要使用javasricpt检查所做的任何更改

解决方案


  • 您正在使用字符串值覆盖 HTMLInputElement ,因此会出现错误。

  • 使用 onchange 事件以及 document.addEventListener

  • 我已经 DOMContentLoaded 方法可以为您提供更好的主意,而不是使用 window.onload



  document.addEventListener('DOMContentLoaded',function(){document。 querySelector(#yourGuess)。onchange = check;},false);函数check(event){if(event.target.value> 10 || event.target.value< 0){alert(数字必须介于0到10之间); event.target.value = 0; }}  

 < label for = yourGuess>您选择:< / label><输入id = yourGuess type = number min = 0 max = 10>  


window.onload = function init() {
  console.log("DOM is ready!");
  var input, value;
  
  input = document.getElementById("yourGuess");
  input = input.value;
  
  input.addEventListener("checking", check, false);
  
  check(value);
  
}

function check(value) {
  if(input < 0 && input > 10) {
    alert("The number must be between 0 - 10");
    value = 0;
  }
}

<label for="yourGuess">You choose: </label>
<input id="yourGuess" type="number" min="0" max="10">

I can't find any solution anywhere that correspond to the issue above.

So I have a number type input and declared a min and max attribute with the value 0 and 10 respectively.

The user can click the input field and change its value outside of range, hence I need to use javasricpt to check any changes made

解决方案

  • You're overwritting your HTMLInputElement with the value which is string, hence you're getting error.
  • Use onchange event along with document.addEventListener.
  • I've DOMContentLoaded method which gives you better idea instead of using window.onload!

document.addEventListener('DOMContentLoaded',function() {
    document.querySelector("#yourGuess").onchange=check;
},false);

function check(event) {
   if(event.target.value > 10 || event.target.value < 0){
      alert("The number must be between 0 - 10");
      event.target.value = 0;
   } 
}

<label for="yourGuess">You choose: </label>
<input id="yourGuess" type="number" min="0" max="10">

这篇关于纯javascript检测数字输入值的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆