在HTML编辑表单上,有什么方法可以重置并记住发布的值功能?

时间:2013-03-25 02:38:58

标签: forms

我有一个同时具有服务器端和客户端验证的表单。 它是一个编辑表单,因此原始用户值最初是预先填充的。

e.g. The original pre-populated values are:
username = yeo
surname = yang
phonenumber = 11-12345

现在,用户编辑到下面并提交。

e.g. The edited submitted values are:
username = yeoNew
surname = yangNew
phonenumber = 12-1111

这会被提交到服务器端并且无法通过服务器端验证,因为不允许以12开头的电话号码。

无论如何,表单会以

的形式显示给用户
e.g. The redisplayed form values are:
username = yeoNew
surname = yangNew
phonenumber = 12-1111

这是因为我的表单允许用户记住他们提交的值。

在此阶段,我想让用户能够使用clientside javascript将表单值重置为原始值。这就像重置功能。<​​/ p>

e.g. The reset button will restore the form values to:
username = yeo
surname = yang
phonenumber = 11-12345

此重置功能的原因是我希望用户可以选择从原始值再次编辑电话号码。

我的问题是: 什么是跟踪HTML中原始值的好方法,以便我可以使用javascript恢复它?

我正在考虑在表单元素中使用一个名为orig =''的新属性来存储该值。 这是一个好主意吗? 还有其他方法吗?

感谢

1 个答案:

答案 0 :(得分:1)

我会使用HTML5本地存储。 见http://www.w3schools.com/html/html5_webstorage.asp

使用jquery我会这样做:

   <script type="text/javascript">
      function load() {
        if (localStorage["username"]) {
            $('#username').val(localStorage["username"]);
        }
        if (localStorage["surname"]) {
            $('#surname').val(localStorage["surname"]);
        }
        if (localStorage["phone"]) {
            $('#phone').val(localStorage["phone"]);
        }
      }

      function save() {
        localStorage["username"] =  $('#username ').val();
        localStorage["surname"] =  $('#surname').val();
        localStorage["phone"] =  $('#phone').val();
      }
   </script>