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

荒凉一梦 提交于 2019-12-09 03:31:05

问题


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.



来源:https://stackoverflow.com/questions/20446948/why-does-jquery-val-function-not-update-attribute-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!