Search code examples
javascriptselectjquery-chosenpyrocms

Updating selected value of a dropdown list with jQuery in PyroCMS


I am facing a little problem in the development of a module for PyroCMS.

I want to update a dropdown list dynamically using jQuery. I would like to set the selected option, but it does not seem to work since the dropdown list is not the default one of the browser.

I tried this :

$('select[name=item-type] option[value='+type+']').attr('selected', 'selected');

but the UI isn't updated.


Solution

  • Finally I found the solution.

    The dropdown custom UI is powered by a plugin called Chosen.

    Editing the DOM element does not update the Chosen dropdown UI because this plugin does not dynamically spy on its attached <select>. You need to tell explicitely Chosen that you have just updated the DOM by firing an event.

    Until version 2.3 PyroCMS uses Chosen 0.9, so you may trigger the event like that:

    $('select.any-selector').trigger("liszt:updated");
    

    To be complete, with Chosen 1.0 the event has changed, and you must use:

    $("select.any-selector").trigger("chosen:updated");
    

    References: