Search code examples
jqueryhtmlcustom-attributestextinputrevert

Setting the value of textboxes with one of their attributes (jQuery)


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.


Solution

  • 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].