Question

I have an HTML control:

<select id="grade">

I want to get the selected value of dropdown on selected Index changed event.

I tried to add following code which would be called on drop down selection change, but seems it doesnot work. Any other suggestion ?

$("#grade").on('change', function() { 
alert("hi"); 
});

Also, how can I get the selected value in Java Script.

Was it helpful?

Solution

If ID=grade doesn't exist when code is run, you need to delegate the handler to a permanent asset in the page. This can be any element selector up the tree from your eleemnt or body or document itself. This method will work regardless if selector already exists, or will exist in future

$(document).on('change',"#grade", function() { 
     alert( $(this).val())
});

If the ID does exist, your code should work so long as you have wrapped it in *document.ready*

$(function(){
/* your code*/

})

OTHER TIPS

Here is an alternative for those who don't need jQuery:

<select id="grade" onchange="OnGradeChanged(this.value);">
     <option value="1">1</option>
     <option value="2">2</option>
</select>
<script>
function OnGradeChanged(value){
     alert(value);
}
</script>

You can also try:

$(document).ready(function(){
  $('#grade').change(function() {
    alert('Handler for .change() called.');
    alert($(this).val()); 
  });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top