How to set value in dropdown menu using jQuery?

Hey. I set the value in the dropdown using jquery in the following ways.

$("#dropDownItems option[value='--Select--']").attr('selected', 'true'); $("#dropDownItems option[value='--Select--']").attr('selected', 'selected'); 

But none of them work for FireFox! and works great for the remaining browsers.

Can anyone help me out?

+6
source share
5 answers

This should do the trick for you.

 $('#dropdownID').val("Value to be selected"); 
+11
source
 $("#dropDownItems").val("--Select--"); 

Or, if you just want to select the first option regardless of its value, you can define this helper function:

 $.fn.selectFirst = function () { return $(this).find("option:first").attr("selected", "selected").end(); } 

Then use it as follows:

 $("#dropDownItems").selectFirst(); 
+3
source

If you want to set the default and this is the first element, you can do:

 $('#dropDown')[0].selectedIndex=0; 
+1
source

I think there are several ways to do this. The easiest way:

 $("#dropdownID").val("dropdownValue"); 

This will work fine, but it will not fire the change event, if any. To solve the problem, use it as shown below:

 $("#dropdownID").val("dropdownValue").change(); 

Other possible ways:

 $("#dropdownID").attr('selected','selected'); $("#dropdownID").prop('selected', true); 
0
source

try it

 $('[id*=_dropdown]').val("--Select--"); 
0
source

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


All Articles