Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .data() not working with $(this)

Tags:

html

jquery

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?

like image 457
Ze Jibe Avatar asked Apr 01 '13 14:04

Ze Jibe


3 Answers

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.

like image 159
Fabrício Matté Avatar answered Oct 28 '22 18:10

Fabrício Matté


How about something like this

$('input').each(function(){$(this).data('initial-value',$(this).val());})
like image 22
Chen Kinnrot Avatar answered Oct 28 '22 18:10

Chen Kinnrot


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 ;)

like image 23
Niet the Dark Absol Avatar answered Oct 28 '22 17:10

Niet the Dark Absol