Javascript select onchange get value, with dropdownlist

Lionsure 2020-06-13 Original by the website

The selected value of the drop-down list box (select/dropdownlist) is generally got on the server, but sometimes it needs to be got on the client. For example, if there are three levels, it need to got on the client with javascript. The dropdownlist is the server control of asp.net, and will eventually be parsed as select, and the id will not change, so it is the same as getting the value of select.

How to get selected value from select/dropdownlist in javascript, is it the same as getting the value of textbox? It can only be said that there are similarities, and more of them are different; the same is to get their id, and then take the value according to the object; the difference is: the value of textbox can be directly got by id.value, and the selected value of select/dropdownlist cannot be directly got with id.value, so how should it be got? See the specific example below.

 

1. Javascript select onchange get value

Html code:

<select id="selectId" onchange="ShowSelectValue()">
              <option value="0">Please select</option>
              <option value="1">item 1</option>
              <option value="2">item 2</option>
       </select>

 

Javascript code:

<script type="text/javascript">
       function GetSelectValue(obj) {
              var selectObj = document.getElementById(obj);
              return selectObj.options[selectObj.options.selectedIndex].value;
       }
       function ShowSelectValue() {
              alert(GetSelectValue("selectId"));
       }
       </script>

The above code is copied into the html file to directly display the current selected value of select. It can be seen from the value to be got in javascript: after the select object is got by id, the select index of select is first got, and then the index is used to got the select value.

 

2. How to get selected value from dropdownlist in javascript

Front code:

<asp:DropDownList ID="ddlId" runat="server">
              <asp:ListItem Text="Please select" Value="0" />
              <asp:ListItem Text="item 1" Value="1" />
              <asp:ListItem Text="item 2" Value="2" />
       </asp:DropDownList>

The javascript method to get the selected value of dropdownlist is the same as above, just call the GetSelectedValue(obj) method above, the calling code is as follows:

GetSelectValue("ddlId");