views:

146

answers:

4

I have a bunch of input text boxes that have the attribute ORIGINAL set to their initial value, so that when the user changes the textbox value, jQuery can highlight items that have changed (by comparing the text box's current value to the ORIGINAL attribute's value)

What Im trying to do now is provide the user with a button that they can click to revert all text boxes back to their original values based on the value of the ORIGINAL attribute of each text box.

Example

$('input[type=text]').val($(this).attr('original'));

The above doesnt work and I dont understand why.

A: 

Something like this:

$('input[type=text]')each(function(){$(this).val($(this).attr('original'));}
LymanZerga
+2  A: 

Use each:

$('input:text').each(function() {
    $(this).val($(this).attr('original')); // or this.value = $(this).attr('original');
});

You can't use a one-liner, as $('input[type=text]').val() will return only the value of the first element in the matching collection. $(this) does not mean what you think it does in your example:

$('input[type=text]').val($(this).attr('original'));

It in fact refers to the current scope. When you iterate over a collection using each jQuery will invoke it's callback and assign the current element in the iteration as the current scope ($(this) or this).

As a side-note, input:text is a prettier, more concise way of saying input[type=text].

karim79
I'd use `this.value = $(this).attr("original") || ""` in the each loop though. No need to send jQuery through its `.val()` hoops to just set the value.
David Murdoch
@David - I've thrown that in as a code comment. I wouldn't call `$(this).val()` much of a hoop though, but I will admit that `this.value` is easier to type and somewhat easier on the eyes.
karim79
A: 

You can call .defaultValue on any input to get its original value

Gareth
A: 

val accepts a function:

$('input:text').val(function () {
    return $(this).attr('original');
});
Matt