简体   繁体   English

如何使用javascript检查和更改输入的值

[英]How do I check and change the value of an input with using javascript

If user types in a value more than 5, I want to set it to 5. 如果用户输入的值大于5,我想将其设置为5。

 function maxValCheck() { if (document.getElementById('xxx').value > 5) { document.getElementById('xxx').value = 5; } } 
 <input id="xxx" type="number" onkeypress="maxValCheck()" max="5" min="1" value="1" /> 

只需将事件更改为onkeyup

<input id="xxx" type="number" onkeyup="maxValCheck()" max="5" min="1" value="1"/>

You can select the element by getElementById or from the querySelector and need to specify the event that you're going to trigger as the first parameter and second parameter is the function that you're going to execute on the added method in addEventListener. 您可以通过getElementById或从querySelector中选择元素,并需要将要触发的事件指定为第一个参数,第二个参数是要在addEventListener中添加的方法上执行的函数。

<input id="xxx" type="number" max="5" min="1" value="1" />

<script>
    const selectElement = document.querySelector('#xxx');
    selectElement.addEventListener('change', function (evt) {
        console.log("value is changing in input");
    });

    // or

    document.getElementById("xxx").addEventListener('change', function (evt) {
        console.log("value is changing in input");
    });
</script>

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

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