I want to store the initial data of my input
fields (to be able to check against these initial values later on). Therefore, I use the following code snippet when my page loads:
$(document).ready(function () {
$('input').data('initial-value', $(this).val() )
}
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.
The following does work:
$('input').data('initial-value', 'whatever value' )
Can't I use the jQuery $(this)
operator inside the .data()
method? If so, what else could I do?
You will need some iteration for that, and .each
will also set the correct this
reference for you:
$('input').each(function() {
$.data(this, 'initial-value', this.value);
});
Fiddle
I've used the static $.data
method which provides better performance, but you can use $(this).data('initial-value', this.value)
as well.
Also, this.value
will do nicely and provides much better performance than $(this).val()
- the drawback is when you have select
element with the multiple
property for which .val()
returns an array with the selected values while .value
returns the first value only.
Though, you can get the initial value through the element's defaultValue
property. E.g.:
console.log( $('input')[0].defaultValue );
Fiddle
Note that this approach will not work for select
elements. This would require iterating over the select's option
elements and checking their defaultSelected
property, but in that case it is easier to go with the former solution.
How about something like this
$('input').each(function(){$(this).data('initial-value',$(this).val());})
In this case, this
refers to the global object since there is no context.
Besides, you don't need this. Just .attr("value")
will give you the initial value ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With