How to assign an empty value to select a drop-down list?

This works with Google Chrome and IE, but not with Firefox. For some realities, Chrome and IE allow you to assign an empty value, although it is not part of the drop-down list.

document.getElementById('dropdownid').value = ""; 

Please note that I have access to jQuery, but I am not doing what I need.

 $("#dropdownid").val(""); 

The above jQuery does not set it to an empty value, since an empty value is not part of the drop-down list. I need to assign a "" to the dropdown selected value due to some issues with legacy third party code.

Any idea?

+6
source share
7 answers

Setting selectedIndex to -1 cancels the selection.

 document.getElementById('dropdownid').selectedIndex = -1; 
+8
source

Just change selectedIndex . For instance:

 $(function(){ $dropdown = $("#dropdownid"); alert($dropdown.val()); //alerts "2" $dropdown[0].selectedIndex = -1; //or document.getElementById('dropdownid').selectedIndex = -1; alert($dropdown.val()) //alerts null }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select id="dropdownid"> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> </select> 

http://jsfiddle.net/kxoytdg8/

+2
source

Could you add an empty parameter to select before configuring it?

 var jqDropdown = $('#dropdownid'); if (!jqDropdown.find('option[value=""]').length) { jqDropdown.prepend($('<option value=""></option>')); } jqDropdown.val(""); 
0
source

Have you tried not to select options in the list?

$("#dropdownid option").prop("selected", false);

0
source

The best way is to use $("#dropdownid").html(''); it makes null.

0
source

2018 jQuery 3.2.1 answer

If you combine the methods in the jquery selector, $('#selectId').slideUp(600)[0].selectedIndex = -1 seems to work (at least in Chrome) but prevents my 'stick to one syntax / frame preference .

This also works: $('#selectId').slideUp(600).find('option[selected]').attr('selected', false);

It's a little longer, but choose the flavor that you prefer.

0
source

You can try
$("#elementId").val('');
for example, $("#CountryDD").val('');

0
source

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


All Articles