Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the selected value on select tag using JavaScript?

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?

like image 820
user2545177 Avatar asked Jul 05 '13 04:07

user2545177


2 Answers

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;
like image 80
Seth Avatar answered Nov 09 '22 22:11

Seth


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;
like image 43
Vijay Avatar answered Nov 10 '22 00:11

Vijay