views:

71

answers:

4

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?

Muchos gracias mi amigos

+5  A: 

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.

Nick Craver
A: 

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();
Herman
A: 

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");
Andrew Dunn
He intends to *get* the value, that's not the problem...it's that `.attr()` isn't even a valid method on the DOM element :)
Nick Craver
Oh I see now, I just assumed he was using jQuery so I didn't look at his code and spot the non-jQueryness. Thanks :)
Andrew Dunn
A: 

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');
Lime