Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jQuery val() function not update attribute 'value'?

Tags:

jquery

attr

input

I came across with this issue way after I completed the website since I had to implement history in ajax based page (which requires to update certain places with html (which includes forms with simple text inputs - that's where the problem - they don't get their values assigned, because they have their values set by val() and not by attr() - lies)). Am I doomed to have to replace all javascript from

$('#xxx').val('someValue');

to

$('#xxx').attr('value', 'someValue');

or there is some hope to bypass this?

A pretty trivial example here. As you can see in the dialog, attribute value is not set in html code.

like image 415
Andrius Naruševičius Avatar asked Dec 07 '13 21:12

Andrius Naruševičius


1 Answers

It uses the underlying native element.value = 'someValue' that of course sets the value property of the element

element.property_to_set = 'new_value';

so it does not change the attribute, that would be

element.setAttribute('value', 'someValue')

which is what attr() does internally, while prop() changes the property, just like val().
The reason it changes the property, is that the property is what is used in a form submit, and it's normally what is used to get the value back in javascript as well, so it makes sense to stick with the property and not the attribute, as the attribute is normally just used to set the initial value of the property, and changing the attribute later with javascript does not update the property, which would be the opposite problem of the one you're having, and it would affect all form submits and be a major issue.

like image 151
adeneo Avatar answered Jan 01 '23 21:01

adeneo