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条回答
Melony?
2楼-- · 2019-03-17 13:53

The DOM element has the attribute "value" which you can access by:

element.getAttribute('value');

... which may be different from the element's property value.

Demo

Note that you may call .setAttribute('value', 'new value') which will actually affect any form.reset() that is called after.

查看更多
Juvenile、少年°
3楼-- · 2019-03-17 13:56

Input element got property called defaultValue that is storing the original value.

To reach it via jQuery, just use .prop():

var value = $(this).prop("defaultValue");

Updated jsFiddle - after changing to "two", the above will return "one".

查看更多
时光不老,我们不散
4楼-- · 2019-03-17 13:58

Try this:

$("#one")[0].defaultValue;
查看更多
孤傲高冷的网名
5楼-- · 2019-03-17 14:03

You could try storing the value in data. For example:

$('#one').data('val',$('#one').val());

And then you could easily retrieve it later like this:

console.log($('#one').data('val'));
查看更多
来,给爷笑一个
6楼-- · 2019-03-17 14:03
var initialVal = $('#one').val();
alert(initialVal);
$('#one').live("focusout", function() {
    var attribute = $("#one").attr("value");
    var value = $(this).val();
    var get = $(this).get(0).value;
    alert( "Attribute: " + attribute + "\n\nValue: " + value + "\n\ninit val: " + initialVal +"\n\nGet: " + get );
});
查看更多
Deceive 欺骗
7楼-- · 2019-03-17 14:04
Save the original_values @ document.ready.

$(function(){
  var original_values = $.map($('form input'), function(input){ return $(input).val() });
})
查看更多
登录 后发表回答