数字类型输入的 onkeyup 与 onchange [英] onkeyup vs onchange for number type input

查看:28
本文介绍了数字类型输入的 onkeyup 与 onchange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在处理表单上的数字输入时遇到了一个小问题,特别是在用户修改它们时尝试调用验证 js 函数时.

此方法仅在用户在框中键入数字时调用,并且在用户使用浏览器提供的向上/向下按钮时被忽略.所以它并不完全有效.

此方法非常适合使用向上/向下按钮的用户,但如果他们在框中输入数字,则在移动到另一个元素或在框外单击之前不会执行该方法.这不是世界末日,但我希望用户能够在框中输入并立即能够单击当前禁用的提交按钮,而不必单击其他地方以启用该按钮.

因此,为了获得最佳的用户体验,我正在这样做.问题是该函数经常被调用两次.我猜它工作正常.用户甚至没有注意到它运行了两次.尽管如此,我似乎还是遗漏了一些东西,必须有一些正确"的方法来处理这个问题.

有吗?或者这只是我们必须解决的问题之一?

解决方案

您可以使用 oninput 事件.

function validateForm() {console.log('改变');}

I'm having a small issue dealing with number inputs on forms, specifically when trying to call a validation js function when the user modifies them.

<input type="number" name="somenumber" onkeyup="validateForm()" />

This method only calls if the user types a number in the box and is ignored when the user uses the up/down buttons supplied by the browser. So it isn't fully effective.

<input type="number" name="somenumber" onchange="validateForm()" />

This method works great for users using the up/down buttons, but if they type a number into box, it won't execute until they move to another element or click outside the box. It's not the end of the world, but I'd like users to be able to type in the box and immediately be able to click the currently disabled submit button, rather than having to click elsewhere to enable the button.

<input type="number" name="somenumber" onchange="validateForm()" onkeyup="validateForm()" />

So to get the best possible user experience, I'm doing this. The problem is that the function often gets called twice. It works fine I guess. The users don't even notice it's running twice. Still, it seems like I'm missing something and there must be some "right" way to deal with this.

Is there? Or is this just one of those things we have to work around?

解决方案

You could use the oninput event.

function validateForm() {
  console.log('changed');
}

<input type="number" name="somenumber" oninput="validateForm()" />

这篇关于数字类型输入的 onkeyup 与 onchange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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