SA.
SA.

Reputation: 752

javascript function not getting dropdown text

i am using javascript to get the text of selected item from dropdown list. but i am not getting the text. i am traversing the dropdown list by name..

my html dropdownlist is as:

<select name="SomeName" onchange="div1();">
    <option value="someVal">A</option>
    <option value="someOtherVal">B</option>
    <option value="someThirdVal">C</option>
</select>

and my javascript is as:

function div1() {     
     var select = document.getElementsByName("SomeName");     
     var result = select.options[select.selectedIndex].text;
     alert(result);
 }

can you please help me out..

Upvotes: 0

Views: 7019

Answers (3)

James Hill
James Hill

Reputation: 61792

Option 1 - If you're just looking for the value of the selected item, pass it.

<select name="SomeName" onchange="div1(this.value);">
    <option value="someVal">A</option>
    <option value="someOtherVal">B</option>
    <option value="someThirdVal">C</option>
</select>

function div1(val)
{
    alert(val);
}

Option 2 - You could also use the ID as suggested.

<select id="someID" name="SomeName" onchange="div1();">
    <option value="someVal">A</option>
    <option value="someOtherVal">B</option>
    <option value="someThirdVal">C</option>
</select>

function div1()
{
    var ddl = document.getElementById("someID");
    var selectedText = ddl.options[ddl.selectedIndex].value;

    alert(selectedText);
}

Option 3 - You could also pass the object itself...

<select name="SomeName" onchange="div1(this);">
    <option value="someVal">A</option>
    <option value="someOtherVal">B</option>
    <option value="someThirdVal">C</option>
</select>

function div1(obj)
{
    alert(obj.options[obj.selectedIndex].value);
}

Upvotes: 3

jglouie
jglouie

Reputation: 12880

The problem with the original snippet posted is that document.getElementsByName() returns an array and not a single element.

To fix the original snippet, instead of:

document.getElementsByName("SomeName");   // returns an array

try:

document.getElementsByName("SomeName")[0];  // returns first element in array

EDIT: While that will get you up and running, please note the other great alternative answers here that avoid getElementsByName().

Upvotes: 0

Jeroen
Jeroen

Reputation: 63719

getElementsByName returns an array of items, so you'd need:

var select = document.getElementsByName("SomeName");      
var text = select[0].options[select[0].selectedIndex].text;     
alert(text);

Or something along those lines.

Edit: instead of the "[0]" bit of code, you probably want either (a) to loop all items in the "select" if you expect many selects with that name, or (b) give the select an id and use document.getElementById() which returns just 1 item.

Upvotes: 1

Related Questions