5

I have a select statement like this:

<select onchange="change_session()" name="select_path" id="select_path">
    <option name="sserver_id" id="select_path" selected value="{{ i.id }}">{{ default_server_id }}</option>
    {% for i in all_server_id %}
        <option name="server_id" id="select_path" value="{{ i.id }}">{{ i.session_name }}</option>                 
    {% endfor %}
    </select>

The first option show the default_id on the top and the second options lists all the options. User can change the option and process accordingly which is send to server using AJAX. Now I want to find out which server_id has user selected using JavaScript like this:

var serverId=document.getElementById('server_id');

How can I get the selected option?

1

3 Answers 3

7

First, you need to remove the 'name' and 'id' attributes from your <option> tags. You cannot have duplicate ids on a single page.

Next, you can use this to get the element by id:

var selected = document.getElementById('select_path').value;
Sign up to request clarification or add additional context in comments.

Comments

4

try this..

<select onchange="change_session()" name="select_path" id="select_path">
    <option  selected value="{{ i.id }}">{{ default_server_id }}</option>
    {% for i in all_server_id %}
        <option  value="{{ i.id }}">{{ i.session_name }}</option>                 
    {% endfor %}
</select>

code for javascript function

var serverId=document.getElementById('select_path').value;

1 Comment

Where does server_id come from?
1

use this

<select id="MySelectOption">
    <option value="1">test1</option>
    <option value="2" selected="selected">test2</option>
    <option value="3">test3</option>
 </select>

javascript

<script>
       var e = document.getElementById("MySelectOption");
         var strUser = e.options[e.selectedIndex].value;
 </script>
If you would like to get the actual text from the selected option do this:
<script>
       var e = document.getElementById("MySelectOption");
        var strUser = e.options[e.selectedIndex].text;
 </script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.