Removing and Reapplying Widget on an Element

user1388314 picture user1388314 · May 22, 2012 · Viewed 19.1k times · Source

I have got a problem. I am applying the widget on select element. When I am reloading the same select element values, I am removing the widget on the select element and reapplying. But while reapplying the widget on the same element, the changes are not reflecting.

Below is the HTML select statement:

<select id="countries" class="multiselect" multiple="multiple" name="countries">
        <option value="USA">United States</option>
        ...
</select>

To apply the widget on the same element:

function applyWidget(){ 
    $(".multiselect").multiselect();
}

Once the widget is applied, it is creating a div with class=".ui-multiselect".

To remove the widget class:

function removeWidget(){
    $(".ui-multiselect").remove();
}

Calling the applyWidget() method for the first time is working fine. Calling the second time is not working. How do I reload the widget on the element?

Answer

saluce picture saluce · Apr 17, 2013

First, your widget needs to have a destroy method available, and how you do that depends on whether you are using jQueryUI 1.8 and below or jQueryUI 1.9 and above.

For these examples, I'm making the assumption that you are referencing the multiselect div with the following code:

_create: function () {
    this.multiselect = $("<div>").addClass("ui-multiselect")...
}

If you are using jQuery 1.8, your widget should define destroy:

destroy: function()
{
    this.multiselect.remove();
    $.Widget.prototype.destroy.call(this);
}

Otherwise, under jQuery 1.9+, you need to define _destroy:

_destroy: function () 
{
    this.multiselect.remove();
}

Note that you only include one of the two above methods, depending on your version of jQueryUI, and that the 1.9 version is preceeded by an underscore _. Under jQueryUI 1.9, do not define destroy without the underscore, because the widget factory defines that method and you will overwrite (and break) the method.

Once that is complete, you need to change your code so that you "destroy" the widget before recreating it.

function removeWidget(){
    $(".multiselect").multiselect("destroy");
}