Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .attr('value', 'new_value') not working?

I am trying to dynamically change the actual HTML value attribute of an input using jQuery. Although using input.attr('value', 'myNewVal'); works to change it visually, when I inspect the source using Developer Tools in Chrome, the HTML attribute hasn't changed.

Since I'm doing a check in some PHP later on to see if the input has its original value, I need a way of changing the actual HTML attribute, ideally in jQuery. Has anyone else encountered this annoying bug and do any of you guys know a workaround?

I've also tried with .val() and the same happens - the underlying HTML attribute is unchanged.

like image 639
BenM Avatar asked Mar 31 '11 22:03

BenM


3 Answers

Use .val().

input.val("some text");

Based upon your comment, the view source will most likely not be updated. If you are still getting the original value, something else must be going on and more details most likely will be required.

jsfiddle goodness.

like image 72
Mark Coleman Avatar answered Oct 15 '22 09:10

Mark Coleman


This is not a bug. The value attributte is not supposed to change.

The input control is a bit special. According to the HTML spec, the value content attribute gives the default value of the input element. You can see the actual control value which has been set programatically or changed by user in the DOM explorer. When the form is reset the value of the element is set to the value of the value content attribute. (too many values here :))

This is the standard behaviour for all VISIBLE input types. (try setting value for a HIDDEN element and value content attribute will be updated ... in Firefox at least).

like image 39
Corneliu Avatar answered Oct 15 '22 08:10

Corneliu


Don't use .attr() to change the value, use .val(), which was made specifically for this purpose:

input.val("new value");
like image 35
Alex Avatar answered Oct 15 '22 08:10

Alex