...

View Full Version : Selecting a dropdown option by its text



Kosko
07-15-2009, 04:19 PM
So I've got some simple javascript functions to set dropdown selections based on index. But I've also have a field that needs to be selected based on its text (possibly value, but text would be better).

The current code is really just based around this line:

document.getElementById("Option3")[myOption1].selected = true;

and what I'm looking for is:

document.getElementById("Option3").getIndexByText("TheSelectorText").selected = true;

Is there a built in function for this? Has anyone implemented it? I searched google and there didn't seem to be any standout answers.

Thanks!

Philip M
07-15-2009, 04:42 PM
There are several ways to do this:-


<form name='myform'>
<select name = 'list1' id = 'list1' onchange = "rem(this)">
<option selected value=""> Choose A Fruit</option>
<option value='Mango'> Mango </option>
<option value='Apple'> Apple </option>
<option value='Orange'> Orange </option>
</form>

<script type = "text/javascript">
function rem(which) {

var si = document.myform.list1.selectedIndex;
var txt1 = document.myform.list1[si].text;
alert ("Text 1: " + txt1);

var txt2 = document.getElementById("list1").options[si].text;
alert ("Text 2: " + txt2);

var txt3 = which.options[which.selectedIndex].text;
alert ("Text 3: " + txt3);
}

</script>


"Remember that there is nothing stable in human affairs; therefore avoid undue elation in prosperity, or undue depression in adversity". Socrates - Greek philosopher in Athens (469 BC - 399 BC)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum