jQuery – find select element selectedIndex, value and text

jQuery code to access select element’s selected index, selected value and selected option node text.

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

<select id="select1">
<option value="valA">optionA</option>
<option value="valB">optionB</option>
<option value="valC">optionC</option>
</select>
<pre id="msg"></pre>

<script>
function display_selected_info() {
  var selIndex = $("#select1").prop('selectedIndex');
  var selVal = $("#select1 option:selected").val();
  var selText = $("#select1 option:selected").text();
  $("#msg").text("selIndex=" + selIndex + " selVal=" + selVal + " selText" + selText);
}
$(function() {
  display_selected_info();
  $("#select1").change(display_selected_info);
});
</script>
refresh
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments