简体   繁体   中英

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 ifi 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

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/

Just pass the event object into the Endpoint function:

<select onchange="convertDropDownToTextBox(event)">
    <option value="1">Option 1</option>
</select>

And then you can access the value event.target.value from within the function:

function convertDropDownToTextBox(e) {
    console.log(e.target.value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM