3

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);
}
user3594118
  • 191
  • 3
  • 17
  • Perhaps [this](http://stackoverflow.com/questions/4315197/how-to-swap-a-disabled-option-dom-element-to-enabled) can get you started. – chris Jun 05 '14 at 23:37

3 Answers3

1

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.

questing
  • 162
  • 1
  • 10
0

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;
}
Fiddles
  • 2,790
  • 1
  • 32
  • 35
0

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);
}
Mr.Cocococo
  • 1,401
  • 2
  • 11
  • 13