Javascript – disable jquery-chosen dropdown

javascriptjqueryjquery-chosen

I have a select div that I'm using the chosen jquery plugin to style and add features to (most notably, search). The div looks something like this,

 <select data-placeholder="add a foobar" id="foobar" style="width: 350px;">
 <option value=""></option>
 </select>

And I'm using the chosen plugin like this,

 $('#foobar').chosen();

While some AJAX is loading, I'd like to disable the entire <select> div. Maybe with something like this,

 $('#foobar').disable()

or this

 $('#foobar').prop('disabled', true)

I think you get the idea.

Any ideas on how to do this? I've tried a number of different things, like using jquery idioms for disabling things, disabling the <select> which just disables the underlying select, not the chosen stuff on top of it. I've even resorted to manually adding another div with a high z-index to just grey out the box, but I think that this is likely to be ugly and buggy.

Thanks for the help!

Best Answer

You are disabling just your select, but chosen renders it as divs, and spans, etc. So after disabling your select you need to update the plugin to make the select widget disabled too. You can try this way:

$('#foobar').prop('disabled', true).trigger("liszt:updated");

//For non-older versions of chosen you would want to do:

$('#foobar').prop('disabled', true).trigger("chosen:updated");

I found the information here

Fiddle

Once you update the widget all it does is it unbinds the click or other events on the plugin and changes its opacity to 0.5. As there is no real disabled state for a div.