[英]How to disable the drop down menu if no element is there in it
I am working on a project where I want to disable the drop down menu if there is no element added to it ( it will become active after some option is added to it) Like in this example the drop down is empty but its still active ( I am able to click on it). 我正在开发一个项目,我想在没有添加任何元素的情况下禁用下拉菜单(在添加一些选项后它将变为活动状态)就像在这个例子中,下拉列表是空的但它仍然有效(我可以点击它)。 I want to disable that property.
我想禁用该属性。
fiddle example is : http://jsfiddle.net/7aqZm/ 小提琴的例子是: http : //jsfiddle.net/7aqZm/
function myFunction()
{
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option);
}
Using jQuery, you can do something like this: 使用jQuery,你可以这样做:
if ($("option#mySelect").length === 0) {
$("#mySelect").css('display', 'none');
// this hides the select if it's empty
// if you want to disable, comment the previous line
// and uncomment the next one
// $("#mySelect").prop('disabled', 'disabled');
}
You could also look for children in $(#mySelect). 您还可以在$(#mySelect)中查找子项。 You could have the opposite function (starting with the select disabled and enabling it through jquery) with:
您可以使用相反的功能(从禁用选择开始并通过jquery启用它):
$("#mySelect").css('display', 'block') // or 'inline' or...
$("#mySelect").prop('disabled', false); // for enabling
Remember to call this when necessary. 记得在必要时打电话。
You can start by setting the element's disabled attribute. 您可以从设置元素的disabled属性开始。 When you add a new element, you can then remove the disabled property.
添加新元素后,可以删除已禁用的属性。
So: 所以:
<select id="mySelect" size="8" disabled="disabled"></select>
and the javascript: 和javascript:
function myFunction()
{
var x = document.getElementById("mySelect");
x.disabled = false;
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option);
}
And just for a bonus, you could also style the select element using the :empty pseudo-selector (note you have to remove everything between the open and close tags, including whitespace) 只是为了奖励,您还可以使用:empty伪选择器设置select元素的样式(注意您必须删除open和close标记之间的所有内容,包括空格)
css: CSS:
#mySelect:empty {
background-color: red;
}
Check this http://jsfiddle.net/286qL/ 检查这个http://jsfiddle.net/286qL/
Set the disable value equal true, and remove it when the content is added. 将disable值设置为true,并在添加内容时将其删除。
document.getElementById("mySelect").setAttribute('disabled', true);
function myFunction()
{ document.getElementById("mySelect").removeAttribute('disabled');
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.