简体   繁体   中英

.attr(“value”) is always returning undefined?

I have a hidden element and within my jQuery:

<input type="hidden" id="1val" value="24">
var valID = $("#1val").attr("value");

However when I try to print valID it is always printed as undefined? What am I doing wrong?

Thanks

It's always safer to use the .prop() or .val() method to get the current value property:

var valID = $("#1val").val();
// or
var valID = $("#1val").prop("value");

As of jQuery version 1.9, the .attr() method will only get the element's attribute, which may not actually reflect the element's actual property.


According to the version 1.9 release notes , under .attr() versus .prop() :

The value property versus attribute on input elements is another example of this ambiguity. The attribute generally reflects the value that was read from the HTML markup ; the property reflects the current value . Since the .val() method is the recommended jQuery way to get or set the values of form elements, this confusion usually does not affect users.

However, when a selector like input[value=abc] is used, it should always select by the value attribute and not any change made to the property by the user, for example from them typing into a text input. As of jQuery 1.9, this behaves correctly and consistently. Earlier versions of jQuery would sometimes use the property when they should have used the attribute.

Under the hood, as of version 1.9, the .attr() method will only return the current attribute of the element (and not the property). The attribute and the property may not actually be the same. For instance, if there was initially no attribute on the element, and then the value was programatically set using a method such as .val() , then the attribute wouldn't have changed meaning that .attr('value') would return undefined .

As stated above, use the .prop() or .val() method in order to get the element's current value property.

Use $('#input-id').val(); to get value of input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM