将输入设置为最新的有效值

发布于 2024-12-28 18:18:04 字数 298 浏览 3 评论 0原文

我正在尝试为 HTML5 的 input type="number" 元素编写一个polyfill。 这里有一个比较示例(如果您的浏览器已经支持)。

如果您输入的值无法解析为数字,例如“abc”,那么当您进行模糊处理时,Chrome 会将该值设置回您最近使用的有效值。我想我可以通过在字段获得焦点时将值存储在 data- 属性中来做到这一点,以防万一我需要将其设置回来,但是有没有更自然的方法来“记住” “表单字段的最新有效值?

I'm trying to write a polyfill for HTML5's input type="number" element. Here's a comparative example if your browser already supports it.

If you enter a value that cannot be parsed as a number, such as "abc", when you blur, Chrome will set the value back to whatever the most recent valid value you was. I suppose I could do that by storing the value in a data- attribute whenever the field gets focus, just in case I need to set it back, but is there any more natural way to go about "remembering" the most recent valid value a form field had?

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

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

发布评论

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

评论(1

醉殇 2025-01-04 18:18:04

这通常称为撤消此人向您展示如何使用 JavaScript 做到这一点:

<html>
   <head>
      <title>Title</title>
      <script type="text/javascript" language="javascript">
         function InputBalance_OnChange(sender) {
            if(isNaN(sender.value)) {
               sender.value = isNaN(sender.prevValue) ? 0 : sender.prevValue;
            } else {
               sender.prevValue = sender.value;
            }
         }
      </script>
   </head>
   <body>
      <table>
         <tr>
            <td>Account Number</td>
            <td><input id="inputAccountNumber" type="text" /></td>
         </tr>
         <tr>
            <td>Balance</td>
            <td><input id="inputBalance" type="text" onChange="InputBalance_OnChange(this)" value="0" /></td>
         </tr>
      </table>
   </body>
</html> 

This is often called undo. This fellow shows you how to do it with JavaScript:

<html>
   <head>
      <title>Title</title>
      <script type="text/javascript" language="javascript">
         function InputBalance_OnChange(sender) {
            if(isNaN(sender.value)) {
               sender.value = isNaN(sender.prevValue) ? 0 : sender.prevValue;
            } else {
               sender.prevValue = sender.value;
            }
         }
      </script>
   </head>
   <body>
      <table>
         <tr>
            <td>Account Number</td>
            <td><input id="inputAccountNumber" type="text" /></td>
         </tr>
         <tr>
            <td>Balance</td>
            <td><input id="inputBalance" type="text" onChange="InputBalance_OnChange(this)" value="0" /></td>
         </tr>
      </table>
   </body>
</html> 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文