For starters, the code you provided won't work because this
refers to document
instead of the input
element. You'd need to update your code to be:
jQuery(function ($) { //aliasing document.ready shortcut, good practice
"use strict";
$('input').data('initial-value', $('input').val());
});
Of course, that probably won't do what you want either, as it will set every input element to store the initial value of the first input element (.val()
returns the value of the first matched element).
So to update the code to work for every element, you'd use:
jQuery(function ($) {
"use strict";
$('input').each(function () {
$(this).data('initial-value', $(this).val());
});
});
But then we need to get into the question of why you're bothering to store the initial value of the element in the first place. If someone changes the value of the input element with $(someElement).val('new value');
, the input can be reset by setting its value back to it's [value]
attribute:
$(someElement).val($(someElement).attr('value'));
If, on the other hand, you're setting the value of the input
element with $(someElement).attr('value', 'new value');
, you're doing it wrong, and are corrupting your input
element's state. reset
buttons rely on the [value]
attribute preserving the original state so that when a form
is reset, the inputs can be returned to their original state.
You also mentioned:
The problem is that the above does not store the initial value of the input
field in a data attribute initial-value
. The attribute is not created.
When you use .data()
to access data on an element, it will pull information from [data-*]
attributes if [data-*]
attributes are present. This is great for initializing data on an element.
When you use .data(key, value)
to associate data with an element, it will store the value as a property on the element; It will not update the attribute's value. There isn't a way to serialize instantiated objects such as new Foo
in a way that it could be deserialized to the way it was originally.
If you want to verify that an object's data was set correctly, you can't simply use the DOM inspector, you'd need to actually check the contents of .data()
for that particular element.
For more information about the differences between .attr()
and .data()
, see my answer to this related question.