JQuery change event in dropdown menu

I just added the lib request to my web application and tested with a simple warning:

<script src="<c:url value="/resources/jquery-1.10.2.min.js" />"></script> <script type="text/javascript"> $(function(){ alert('jquery is working'); }); </script> 

And it works great. However, when I want to implement the "change" event in my popup menu

 <script src="<c:url value="/resources/jquery-1.10.2.min.js" />"></script> <script type="text/javascript"> $("#projectKey").change(function() { alert($('option:selected', $(this)).text()); }); </script> 

he does not show me any warning, basically nothing happens. My dropdown is as follows:

 <select id="projectKey" name="projectKey"> <option value="AM">AM</option> <option value="AIL">AIL</option> <option value="NEB">NEB</option> <option value="SSP">SSP</option> </select> 

Of course I tried to simplify javascript, just leave

 $("#projectKey").change(function() { alert("test"); }); 

but still no joy. It will be something with a selector or a dropdown. I also tried "select # projectKey", but the result was, of course, the same. Any idea what I'm doing wrong?

+6
source share
4 answers

You should have saved this ready-made DOM function

 $(function() { $("#projectKey").change(function() { alert( $('option:selected', this).text() ); }); }); 

The document is not ready, if you added javascript before the elements in the DOM, you need to either use the DOM ready function or add javascript after the elements, the usual place is right before the </body>

+22
source

Please change the javascript function as below.

 $(function () { $("#projectKey").change(function () { alert($('option:selected').text()); }); }); 

You do not need to use $(this) in the warning.

+2
source

Or you can use this javascript

 $(function () { $("#projectKey").change(function () { alert($('#projectKey option:selected').text()); }); }); 
+1
source

html

 <select id="drop" name="company" class="company btn btn-outline dropdown-toggle" > <option value="demo1">Group Medical</option> <option value="demo">Motor Insurance</option> </select> 

Script.js

 $("#drop").change(function () { var category= $('select[name=company]').val() // Here we can get the value of selected item alert(category); }); 
0
source

All Articles