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:23

jquery - Get the value in an input text box

<script type="text/javascript"> 

jQuery(document).ready(function(){

var classValues = jQuery(".cart tr").find("td.product-name").text();
classValues = classValues.replace(/[_\W]+/g, " ")

jQuery('input[name=your-p-name]').val(classValues);

//alert(classValues);

});

</script>
查看更多
妖精总统
3楼-- · 2019-01-01 09:25

In attr('value') you're specifically saying you're looking for the value of an attribute named vaule. It is preferable to use val() as this is jQuery's out of the box feature for extracting the value out of form elements.

查看更多
姐姐魅力值爆表
4楼-- · 2019-01-01 09:26

I have always used .val() and to be honest I didnt even know you could get the value using .attr("value"). I set the value of a form field using .val() as well ex. $('#myfield').val('New Value');

查看更多
公子世无双
5楼-- · 2019-01-01 09:29

The proper way to set and get the value of a form field is using .val() method.

$('#field').val('test'); // Set
var value = $('#field').val(); // Get

With jQuery 1.6 there is a new method called .prop().

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.

查看更多
孤独寂梦人
6楼-- · 2019-01-01 09:31

There is a big difference between an objects properties and an objects attributes

See this questions (and its answers) for some of the differences: .prop() vs .attr()

The gist is that .attr(...) is only getting the objects value at the start (when the html is created). val() is getting the object's property value which can change many times.

查看更多
呛了眼睛熬了心
7楼-- · 2019-01-01 09:31

If you get the same value for both property and attribute, but still sees it different on the HTML try this to get the HTML one:

$('#inputID').context.defaultValue;
查看更多
登录 后发表回答