JQuery: Get original input value

2019-03-17 13:15发布

Is it possible to get the initial value of a form input field?

For example:

<form action="" id="formId">
    <input type="text" name="one" value="one" id="one" />
</form>

$("#one").attr("value");   //would output "one"
$("#one").val();           //would output "one"
$("#one").get(0).value;    //would output "one"

However, if the user then changed the content of the #one input field to two, the html would still look the same (with one as the value) but the JQuery calls above would return two.

JSFiddle to play with: http://jsfiddle.net/WRKHk/

I think that this must still be possible to get the orginal value, since we are able to call document.forms["formId"].reset() to reset the form to its original state.

7条回答
2楼-- · 2019-03-17 14:12

The HTML does change. Just that the browser's default view source tool always shows you the original source fetched from server. If you use something like Firebug, you'll be able to see the dynamic changes in HTML.

One way of getting the initial value is by storing it in an additional attribute in addition to 'value'. For example, if you serve out your HTML like:

<input type="text" name="one" value="one" origvalue="one" id="one" />

You can always get back the original value by calling:

$("#one").attr("origvalue");
查看更多
登录 后发表回答