Reputation: 14422
If I have a text input and have set a default value in the HTML, is there anyway to access the original value after jquery has changed the current value using .val()
?
It was my understanding that jQuery should be changing the value property and not the value attribute?
Edit: Note I'm not asking how I could store the default value to retrieve it later (e.g. in data or in a var) I'm interested in why jQuery is modifying the attribute of the input field (and in turn the defaultValue) and not just the property.
For this example:
<input id="me" type="hidden" value="starting value" />
<script>
var $field = $('#me');
console.log($field.val());
console.log($field.prop('defaultValue'));
console.log($field.val('new value'));
console.log($field.val());
console.log($field.prop('defaultValue'));
console.log($field.attr('value'));
console.log($field.prop('value'));
</script>
We see:
starting value
starting value
[input#me, context: document, selector: "#me", jquery: "2.1.0", constructor: function, toArray: function…]
new value
new value
new value
new value
Fiddle:
http://jsfiddle.net/jLsqmxg7/1/
Upvotes: 2
Views: 937
Reputation: 500
jQuery "val" setter always change both the attribute and the property. They do this to not confuse the developer with a ambiguous behavior. If you really want to change only the property and let the tag attribute with the same value do this:
var $input = $("<input>", {value: 'original'}); // Using the jQuery constructor to create a input :)
$input[0].value = "foo"; // Changing the value property of this HTMLInputElement instance
console.log($input.val()); // foo
console.log($input.prop('value')); // foo
console.log($input.attr('value')); // original
With this, you're changing only the HTMLInputElement value property, not the tag attribute. So, was I say, this turns the code a little confunsing.
Upvotes: 2