Search code examples
javascriptonchangehtml-select

Get value of selected drop down list item


Good Evening, i have these dynamically generated dropdown list in my JSP:`

    <td><select name="model" id="model"  onchange="convertDropDownToTextBox()">

                            <c:forEach items="${model_list}" var="item">

                                <option value="${item.modelId}">${item.modelName}</option>
                            </c:forEach>
                                                            <option value="100">Add New Model</option>

            </select></td>

and i tried these script to get the selected value from these dropdown :

function convertDropDownToTextBox(){
    var select = document.getElementById("model");
    var selectedString = select.options[select.selectedIndex].value;
    alert(selectedString);
}

the problem here is that it always gives 1 for every item selected in the dropdown however i f i changed the onChange to be onchange="alert(this.value)" it prints the right values!! how that come? and how to get the actual index of every item selected in the DropDown


Solution

  • Not exactly sure what the problem is but this works for me:

    var select = document.getElementById("model");
    select.onchange = function(){
        var selectedString = select.options[select.selectedIndex].value;
        alert(selectedString);
    }
    

    Demo: http://jsfiddle.net/louisbros/PS4zy/1/