admin管理员组文章数量:1391999
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
4 Answers
Reset to default 7To 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");
本文标签: javascriptjQuery attr() and valueStack Overflow
版权声明:本文标题:javascript - jQuery .attr() and value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744671377a2618843.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论