user3594118
user3594118

Reputation: 201

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/

function myFunction()
{
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option);
}

Upvotes: 3

Views: 1623

Answers (3)

questing
questing

Reputation: 172

Using jQuery, you can do something like this:

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). You could have the opposite function (starting with the select disabled and enabling it through jquery) with:

$("#mySelect").css('display', 'block') // or 'inline' or...
$("#mySelect").prop('disabled', false); // for enabling

Remember to call this when necessary.

Upvotes: 1

Fiddles
Fiddles

Reputation: 2915

You can start by setting the element's disabled attribute. 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:

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)

css:

#mySelect:empty {
    background-color: red;
}

Upvotes: 0

Mr.Cocococo
Mr.Cocococo

Reputation: 1451

Check this http://jsfiddle.net/286qL/

Set the disable value equal true, and remove it when the content is added.

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);
}

Upvotes: 0

Related Questions