How do I get the select box values in YUI 3?

15,849

Solution 1

Once you have the selector, you can chain get and each

Y.get("#regionSelect").get("options").each( function() {
   // this = option from the select
   var selected = this.get('selected');
   var value  = this.get('value');
   var text = this.get('text');
   // apply secret sauce here
});

I've just been using the demos/examples on http://developer.yahoo.com/yui/3/ to figure things out.

Solution 2

// Selected Value

  • Y.one('#regionSelect')._node.value;
  • Y.one('#regionSelect').get('value');

// Selected Index

  • Y.one('#regionSelect')._node.selectedIndex;
  • Y.one('#regionSelect').get('selectedIndex');

Solution 3

You might not need to iterate through all options if you need just a selected one:

var index = Y.get("#regionSelect").get('selectedIndex');
var value = Y.get("#regionSelect").get("options").item(index).getAttribute('value');

Solution 4

You can directly use this. Require selector-css3 module to support IE.

YUI().use("selector-css3", "node", function (Y) {
    var text = Y.one("#ownerSelector option:checked").get("text");
});

http://jsfiddle.net/neosoyn/r8crW/

Share:
15,849
atp
Author by

atp

Updated on July 28, 2022

Comments

  • atp
    atp almost 2 years

    In YUI 3 I have a node that is my select box:

    Y.get('#regionSelect');
    

    How do I get the <option> values that are currently selected (even if there are more than one?) Also, is there a tutorial out there that tells me explicitly how to do this (I don't want to serialize a whole form)?

  • atp
    atp almost 15 years
    Thanks! Where does it say how to get attributes?
  • M.Sworna Vidhya
    M.Sworna Vidhya almost 15 years
    You are welcome. Any JavaScript tutorial about the DOM should have the attribs for the select and option objects (as well as all the others). Those aren't YUI specific but part of the DOM. For instance: w3schools.com/htmldom/dom_obj_select.asp
  • lisak
    lisak over 13 years
    this always returns an empty string...doesn't one have to get the options and then their value ?
  • Nathan
    Nathan over 13 years
    The "_node" property is not part of the YUI Node API. You should never rely on it.
  • Jarod DY Law
    Jarod DY Law over 13 years
    "_node" is visual private object property based on YUI coding standards
  • danjah
    danjah about 13 years
    Did you mean "Y.one("#regionSelect")"? Worked for me when I used .one() instead of .get()