Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing and Reapplying Widget on an Element

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?

like image 873
user1388314 Avatar asked May 22 '12 03:05

user1388314


2 Answers

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");
}
like image 186
saluce Avatar answered Nov 19 '22 21:11

saluce


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

function removeWidget() { 
    $(".ui-multiselect").multiselect("destroy");
    $(".ui-multiselect").multiselect(); 
}
like image 31
jkm Avatar answered Nov 19 '22 21:11

jkm