Quirky jQuery - Setting the 'value' attribute in HTML

Quirky jQuery - Setting the 'value' attribute in HTML

in

This one stumped the guys over at the jQuery IRC channel:

When you use the jquery to set an element's value attribute, you can do the following:

$(this).attr('value', 'newvalue');

or this:

$(this).val('value');

For most attributes, this will change the actual html. To test it out, you can use Firebug and watch the value change, or print out the new output by doing something like:

alert($(this).parent().html());

For the 'value' attribute, however, the html doesn't actually change. And that little quirk cost me a few hours in research to try to find a work-around. What I was trying to do was cache a bock of html in a database, but I wanted to retain the value of the text inputs if they changed. Since the 'value' attribute didn't actually change in the html, I got stuck. Here's what I did to work around it:

  1. Whenever the text changed in the text input, I would create a hidden input with the new value. When the text changed again, the hidden input would be deleted and then added back in. I tried doing this with just the text input (i.e., deleting it, manually adding the value in, and re-outputting it), but when you do that you lose any event bindings. When I went to cache the html, it would look like this:
    <input type="text" name="changing_input" value="Old value" />
    <input type="hidden" rel="changing_input" value="Newly typed value" />
     

  2. Since this is what will be pulled from the database, next I need to trigger a switch to replace out the old value of the text input with the value in the hidden input. That's easy enough with jQuery, since we have a 'rel' attribute to link them.

Personally, I think this is an ugly work-around. Even changing the 'value' attribute with straight javascript didn't seem to work. So, this is really a javascript quirk I'd love to find a better way around.


Discussion on this post:
Implied By Design Logo