Using jQuery to see if the dropdown menu has changed

I would like to see if the selected menu item has been selected or displayed.

I tried

jQuery("#dropdownID option[value='selectionKey']").change(function() { if (jQuery("#dropdownID option[value='selectionKey']").attr('selected', 'selected')) DoSomething(); else DoSomethingElse(); }); 

and

 jQuery("#dropdownID").change(function() { if (jQuery("#dropdownID option[value='selectionKey']").attr('selected', 'selected')) DoSomething(); else DoSomethingElse(); }); 

but not one of the blocks starts, changing the selection in the drop-down menu. That is, it never gets into the if statement.

+6
source share
6 answers

You can try something like this in jQuery version less than 1.7:

 $("#dropdownID").live('change', function() { if ($(this).val() == 'selectionKey'){ DoSomething(); } else { DoSomethingElse(); } }); 

You can try something like this in jQuery version greater than 1.7:

 $("#dropdownID").on('change', function() { if ($(this).val() == 'selectionKey'){ DoSomething(); } else { DoSomethingElse(); } }); 
+13
source

Try the following:

 jQuery("#dropdownID").change(function() { if (jQuery("#dropdownID option[value=selectionKey]").attr('selected', 'selected')) { DoSomething(); } else { DoSomethingElse(); } }); 
+2
source

Try jsFiddle

 <select id="dropdown1"> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select> $(document).ready(function() { $('#dropdown1').change(function() { alert($(this).val()); }); }); 
+2
source

or even less code:

 <select id="dropdown1"> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select> $(function() { //<------- stands for $(document).ready.. $('#dropdown1').change(function() { alert($(this).val()); }); }); 
+2
source

Try the following:

 jQuery("#dropdownID").change(function() { if (jQuery("#dropdownID option[value='selectionKey']").is(':selected')) DoSomething(); else DoSomethingElse(); }); 

But your second method should work if you compare them:

 jQuery("#dropdownID").change(function() { if (jQuery("#dropdownID option[value='selectionKey']").attr('selected') == 'selected') DoSomething(); else DoSomethingElse(); }); 

But it is better to use .prop() , it will return a boolean value:

 jQuery("#dropdownID").change(function() { if (jQuery("#dropdownID option[value='selectionKey']").prop('selected') DoSomething(); else DoSomethingElse(); }); 
+1
source

You need to bind the event to <select> , not to <option> . Also you should just check if this value is valid.

 jQuery("#dropdownID").change(function () { if ($(this).val() === 'selectionKey'){ DoSomething(); } else{ DoSomethingElse(); } }); 
+1
source

Source: https://habr.com/ru/post/948814/


All Articles