Why does jQuery val() function not update attribut

2019-02-21 16:53发布

问题:

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.

回答1:

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.