8

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)?

David Underhill
  • 15,896
  • 7
  • 53
  • 61
atp
  • 30,132
  • 47
  • 125
  • 187

4 Answers4

12

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.

seth
  • 36,759
  • 7
  • 60
  • 57
  • Thanks! Where does it say how to get attributes? – atp Jul 28 '09 at 23:19
  • 1
    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: http://www.w3schools.com/htmldom/dom_obj_select.asp – seth Jul 28 '09 at 23:46
  • The 'selected' and 'text' are actually selectors, not attributes. Left that out.... – seth Jul 28 '09 at 23:50
  • 4
    Did you mean "Y.one("#regionSelect")"? Worked for me when I used .one() instead of .get() – danjah May 13 '11 at 08:29
8

// Selected Value

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

// Selected Index

  • Y.one('#regionSelect')._node.selectedIndex;
  • Y.one('#regionSelect').get('selectedIndex');
Jarod Law Ding Yong
  • 5,697
  • 2
  • 24
  • 16
5

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');
Ruslan Kabalin
  • 6,580
  • 2
  • 28
  • 20
1

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/

Cam Song
  • 2,956
  • 1
  • 22
  • 18