Eslam Hamdy
Eslam Hamdy

Reputation: 7386

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

Upvotes: 2

Views: 41320

Answers (2)

Mayer Spitz
Mayer Spitz

Reputation: 2525

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);
}

Upvotes: 2

louisbros
louisbros

Reputation: 875

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/

Upvotes: 4

Related Questions