Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Nov 2004
    Thanked 0 Times in 0 Posts

    Selecting a dropdown option by its text

    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.


  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    London, England
    Thanked 2,573 Times in 2,551 Posts
    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>
    <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);

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


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts