是否可以设置输入元素的预更改值

发布于 2025-01-07 12:51:34 字数 470 浏览 3 评论 0原文

我有一个带有 onchange 事件的输入元素。如果该值不被接受,onchange 事件会提醒用户,并将焦点返回到输入元素。

但是,如果用户随后单击该元素,则 onchange 事件不会触发 - 这是可以理解的,因为用户没有进行进一步的更改,但它引入了仅验证一次的问题。

我探索了一种可能的解决方案,将值重置回更改前的值,但如果可能的话,我想避免这种情况,以便允许用户更正他们输入的值,而不必键入整个值又是一件事。

另一种可能性是将验证放入模糊事件中,但这会引入其他问题,例如其他元素聚焦时会触发的事件。

所以我的问题是,如果用户将输入值从“X”更改为“Y”,我是否可以将焦点返回到该元素,将该值保留为“Y”,但使其将“X”视为更改前的值,因此,如果用户将其更改回“X”,则更改事件随后不会触发,但如果他们将其保留为“Y”并再次失去焦点,则更改事件会再次触发,就像从“X”更改为“Y”一样'?

I have an input element with an onchange event. The onchange event alerts the user if the value is not accepted, and returns focus back to the input element.

However, if the user then clicks out of the element, the onchange event doesn't fire - which is understandable since the user hasn't made a further change, but it introduces the problem of only validating once.

I explored a possible solution to reset the value back to what it was before it was changed, but I'd like to avoid that if at all possible for the sake of allowing the user to correct the value they entered without having to type the whole thing again.

Another possibility was to put the validation into the blur event but this would introduce other problems such as events on other elements firing if they are focused.

So my question is, if the user changes the input value from 'X' to 'Y', can I return focus to the element, leaving the value as 'Y' but make it treat 'X' as the pre-change value, thus behaving so if the user changes it back to 'X' the change event will not subsequently fire, but if they leave it as 'Y' and lose focus again, the change event fires again as if changing from 'X' to 'Y'?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瑶笙 2025-01-14 12:51:34

为什么不直接将该字段标记为无效(使用 CSS 或 jQuery 添加标记)而不是使用警报?该字段将保持无效,直到用户将值更改为有效值,并且验证脚本会删除无效标记。

Why not just mark the field as invalid (using CSS or jQuery to add markup) instead of using an alert? The field remains invalid until the user changes the value to a valid one, and the validation script removes the invalid marking.

撕心裂肺的伤痛 2025-01-14 12:51:34

输入类型是文本吗?在这些情况下,出于您所描述的原因,我更喜欢使用 onkeyup 而不是 onchange。

有时甚至这也不起作用:当使用鼠标将文本粘贴到文本框中时,这不会捕获更改,因为没有按下某个键(但按下了 shift+insert 或 ctrl+v )。您可能希望将相同的事件添加到 onchange 和 onkeyup 以涵盖所有基础。

Is the input type text? In these circumstances I prefer to use onkeyup instead of onchange for the very reason you're describing.

Sometimes even that doesn't work: This will not capture the change when text is pasted into the text box using a mouse since a key isn't pressed (but shift+insert or ctrl+v are). You might want to add the same event to both onchange and onkeyup to cover all bases.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文