最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery .attr() and value - Stack Overflow

programmeradmin3浏览0评论

I want to make the following use .attr();

selectbox.options[selectbox.selectedIndex].value

sadly,

selectbox.options[selectbox.selectedIndex].attr("value")

is not the same, and seems to defeat the purpose of the .attr altogether. My main question is: How should one use nested .attr()s?

I want to make the following use .attr();

selectbox.options[selectbox.selectedIndex].value

sadly,

selectbox.options[selectbox.selectedIndex].attr("value")

is not the same, and seems to defeat the purpose of the .attr altogether. My main question is: How should one use nested .attr()s?

Share Improve this question edited Dec 24, 2020 at 19:38 Dharman 33.5k27 gold badges101 silver badges148 bronze badges asked Oct 1, 2010 at 21:57 sovasova 5,65811 gold badges42 silver badges50 bronze badges 1
  • JavaScript doesn't have an attr function. jQuery does. I've edited the title. – T.J. Crowder Commented Oct 1, 2010 at 22:05
Add a ment  | 

4 Answers 4

Reset to default 7

To get the value of any type of input element (including <textarea> and <select>) use .val():

var value = $(selectbox).val();

The .attr() translation would roughly be:

$(selectBox).find(":selected").attr("value");

....but just use .val() :)

The basic problem is that .attr() is a jQuery method. It's on jQuery objects, not on DOM elements directly, the same goes for almost all jQuery methods and plugins.

When using attr(), you have to be working with a jQuery object. So first select the relevant select box, then call attr() (or val() in this case, when you need the value of an input element).

var value = $(selectbox).val();

If you would like to retrieve the selected box's value using your current code simply pass it into the jquery object like so.

$(selectbox.options[selectbox.selectedIndex]).attr('value');

The reason they are not the same is because attr('value') gets the value of the value attribute directly from the original HTML code, it is not updated with the DOM, meaning if the value of value is changed after the page has loaded, either by user input (typing into an <input> element, or via manipulation with JavaScript, these changes will not be reflected in the returned value of .attr().

A better way is to use the .val() method of the jQuery object.


Edit To get the attribute of the value from a DOM Element (i.e. not returned by the $() or jQuery() function) use the element.getAttribute() method, which is native, you would use it like this:

selectbox.options[selectbox.selectedIndex].getAttribute("value");
发布评论

评论列表(0)

  1. 暂无评论