Changing Selected Option in a Drop Down Menu in Javascript

0 views
Skip to first unread message

Vivek Chaudhari via StackOverflow

unread,
May 20, 2014, 9:23:50 AM5/20/14
to google-appengin...@googlegroups.com

I may have understood your requirement wrong.

If you want to change the selected item then it is just matter of changing "selected" attribute.

Let say I want to change it to Trillion, then this is how the code will look like:

        <select name='list_" + i + "' id='list'> 
            <option value='0' selected='selected'>Trillion(s)</option> 
            <option value='1' >Billion(s)</option>
            <option value='2'>Million(s)</option>
            <option value = '3'>Below One Million</option>
        </select>

Now let say you want to change the selected item through pure javascript(NO JQUERY)

Here is full example, the selected item will change when you click button. Note: It is just a matter of changing the index.

<head>
    <title> Changing selected option in drop-down menu in JS</title>
    <script type="text/javascript">
        function changeSelected(){ 
            document.getElementById("list").selectedIndex = 1;
        };  
    </script>
</head>

<body>
    <p> Test string....</p>

    <td>
        <select name='list_" + i + "' id='list'> 
            <option value='0' selected='selected'>Trillion(s)</option> 
            <option value='1' >Billion(s)</option>
            <option value='2'>Million(s)</option>
            <option value = '3'>Below One Million</option>
        </select>

        <button onclick="changeSelected()">Try It</button>
    </td>
</body>


Please DO NOT REPLY directly to this email but go to StackOverflow:
http://stackoverflow.com/questions/21566564/changing-selected-option-in-a-drop-down-menu-in-javascript/21566667#21566667
Reply all
Reply to author
Forward
0 new messages