简体   繁体   English

如何分配空值来选择下拉列表?

[英]How to assign empty value to select dropdown?

This works with Google Chrome and IE but not Firefox.这适用于 Google Chrome 和 IE,但不适用于 Firefox。 For some reaons, Chrome and IE allow blank value to be assigned eventhough it is not part of the dropdown selection.由于某些原因,Chrome 和 IE 允许分配空白值,即使它不是下拉选择的一部分。

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

Note that I have access to jQuery but is not doing what i wanted.请注意,我可以访问 jQuery,但没有做我想做的事。

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

The above JQuery does not set it to a blank value because blank is not part of the dropdown options.上面的 JQuery 没有将它设置为空白值,因为空白不是下拉选项的一部分。 I need to assign "" to the dropdown selectedvalue due to some third party legacy code issues.由于某些第三方遗留代码问题,我需要将 "" 分配给下拉选择的值。

Any idea?任何的想法?

selectedIndex设置为 -1 将清除选择。

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

Simply change the selectedIndex .只需更改selectedIndex EG:例如:

 $(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/ http://jsfiddle.net/kxoytdg8/

Couldn't you add a blank option to the select before setting it?在设置之前,您不能在选择中添加一个空白选项吗?

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

您是否尝试过取消选择选择中的选项?

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

best way is to use $("#dropdownid").html('');最好的方法是使用$("#dropdownid").html(''); it makes the value null.它使值为零。

2018 jQuery 3.2.1 answer 2018 jQuery 3.2.1 答案

If you're chaining methods on a jquery selector, $('#selectId').slideUp(600)[0].selectedIndex = -1 appears to work (at least in Chrome) but bothers my 'stick to one syntax/framework' preference.如果你在 jquery 选择器上链接方法, $('#selectId').slideUp(600)[0].selectedIndex = -1似乎工作(至少在 Chrome 中)但困扰我的“坚持一个语法/框架” ' 偏爱。

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

It's a bit longer, but choose the flavor you prefer.时间有点长,但请选择您喜欢的口味。

You can try你可以试试
$(“#elementId”).val('');
eg $(“#CountryDD”).val('');例如$(“#CountryDD”).val('');

//We can set empty dropdown add this code in JS script

$("#dropdownList").empty();
$("#dropdownid option[value='']").attr('selected', true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM