Help on jquery onchange event in dropdown menu

I would like to be able to trigger a warning message every time the value of the drop-down list changes. I thought the code below should work, but this is not for some unknown reason. Any ideas why?

Thanks.

<html> <head> <script type="text/javascript" src="lib/jquery.js"></script> </head> <body> <script type="text/javascript"> $("select").change(function(){ alert(this.id); }); </script> <select> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> </body> </html> 
+7
source share
3 answers

The code is fine, you just do not initialize it correctly.

Try it ....

 $(document).ready(function() { $("select").change(function(){ alert(this.id); }); }); 

see the documentation here .

Your function notifies the id of the select element (which you in no way assigned). I assume you really wanted to get the value from the drop down list? In this case, you want:

 alert($(this).val()); 
+13
source

Register the onchange handler when the DOM is ready to load the page.

 $(function() { $("select").change(function(event) { alert(this.id); // alert( $(this).attr('id') ); to get the id attr with jquery }); }); 

I also suggest targeting the select element with id. Your code will show a warning every time any selection on the page is changed.

+3
source
 $(document).ready(function(){ $("#projectsName").change(function(){ alert("HI"); }); 

});

Please note that project_name is the identifier of the drop-down list and there is no other identifier with the same name; another wise jquery will not work also double check your jquery plugin

0
source

All Articles