jQuery .val() vs .attr(“value”)

2019-01-01 09:01发布

I had thought these two were the same, but they appear to not be. I've generally been using $obj.attr("value") to work with form fields, but on the page I'm currently building, $obj.attr("value") does not return the text I enter in my field. However, $obj.val() does.

On a different page I've built, both $obj.attr("value") and $obj.val() return the text entered in the form field.

What could account for $obj.attr("value") working as expected in one case but not in another?

What is the proper way to set and retrieve a form field's value using jQuery?

标签: jquery forms
14条回答
浮光初槿花落
2楼-- · 2019-01-01 09:41

Since jQuery 1.6, attr() will return the original value of an attribute (the one in the markup itself). You need to use prop() to get the current value:

var currentValue = $obj.prop("value");

However, using val() is not always the same. For instance, the value of <select> elements is actually the value of their selected option. val() takes that into account, but prop() does not. For this reason, val() is preferred.

查看更多
爱死公子算了
3楼-- · 2019-01-01 09:46

In order to get the value of any input field, you should always use $element.val() because jQuery handles to retrieve the correct value based on the browser of the element type.

查看更多
登录 后发表回答