Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the text of a selected item in a select control?

 <select name="DropList" id="serverDropList"> 
  <option selected="selected" value="2">server1:3000</option> 
  <option value="5">server3:3000</option> 
 </select> 

i know in prototype i can get value by $('serverDropList').value but how can i get "server1:3000" ?

like image 478
icn Avatar asked Apr 26 '10 23:04

icn


2 Answers

If you are using Prototype, you may use:

var text = $('serverDropList')[$('serverDropList').selectedIndex].text;
like image 158
multikulinaria Avatar answered Oct 06 '22 13:10

multikulinaria


I don't think Prototype has any shortcut that does that for you, so:

var box = $('serverDropList');
var text = box.selectedIndex >= 0 ? box.options[box.selectedIndex].innerHTML : undefined;

...gives you the innerHTML of the selected option, or undefined if there is none.

If you like, you can use Element#addMethods to define this once and have it available on all of your select boxes:

Element.addMethods("SELECT", (function() {
    function getSelectedOptionHTML(element) {
        if (!(element = $(element))) return;
        var index = element.selectedIndex;
        return index >= 0 ? element.options[index].innerHTML : undefined;
    }

    return {
        getSelectedOptionHTML: getSelectedOptionHTML
    };
})());

Usage:

var text = $('serverDropList').getSelectedOptionHTML();

I used a named function when defining that. If you're not bothered about named functions (I am, I always use them), you can make it a bit simpler:

Element.addMethods("SELECT", {
    getSelectedOptionHTML: function(element) {
        if (!(element = $(element))) return;
        var index = element.selectedIndex;
        return index >= 0 ? element.options[index].innerHTML : undefined;
    }
);
like image 32
T.J. Crowder Avatar answered Oct 06 '22 13:10

T.J. Crowder