Removing and Reapplying Widget on an Element
Asked Answered
S

2

10

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?

Soredium answered 22/5, 2012 at 3:44 Comment(0)
F
13

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");
}
Fideism answered 17/4, 2013 at 16:13 Comment(1)
this worked for me. thanks :) This is completely un-intuitive tbh thoHaig
S
3

You have to destroy the widget or it won't rebind.

function removeWidget() { 
    $(".ui-multiselect").multiselect("destroy");
    $(".ui-multiselect").multiselect(); 
}
Sparkman answered 22/5, 2012 at 20:46 Comment(1)
This won't work, because the multiselect widget is attached to .multiselect, not .ui-multiselectFideism

© 2022 - 2024 — McMap. All rights reserved.