简体   繁体   中英

Read value from select option

I have a following scenario,

<select id="dropDown" onChange="this.options[this.selectedIndex].onclick();>
<c:forEach items="" var="...">
<c:choose>
<c:when test="">
<option id="<portlet:namespace />..." value="red" onclick="<portlet:namespace />SomeFunction(this.id, 'Contants.SOME_ID', '<c:out value="${some_value}"/>)">red</option>
</c:when>
<c:when test="">
<option id="<portlet:namespace />..." value="yellow" onclick="">yellow</option>
</c:when>
<c:when test="">
<option id="<portlet:namespace />..." value="blue" onclick="">blue</option>
</c:when>
</c:choose>
</c:forEach>
</select>

When I select the value say yellow there is no alert at all, only when the page loads first time or if I refresh the page by F5 then I see an alert saying "red". I am not able to alert the selected value.

var selected_item = $('#dropDown').val();
alert(selected_item);

Is there anything I am missing?

EDIT

I have added the sample function for onClick, this is why I use the onClick in the option field. So for each of those I would call different functions. Is there anyway to get the value of the selected option.

<portlet:namespace />SomeFunction(id, some_id, some_value) {

}

Your onclick in the option is doing nothing. Since you are using jQuery, you could not use inline javascript at all.

Remove onChange="this.options[this.selectedIndex].onclick(); and all onclick="" , then try

$(function() {
  $('#dropDown').change(function() {
     alert($(this).val());
  });
});

As you're using jQuery, so you don't need onclick to each option and onChange to select. Remove them and try with .on() using change event.

$('#dropDown').on('change', function() {
   var selected_item = this.value;
   alert( selected_item );
});

If you try to update the value of selected_item variable at page load then you can trigger the change event like following:

$('#dropDown').on('change', function() {
   var selected_item = this.value;
   alert( selected_item );
}).change(); // trigger the change event at page load

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