Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Dialog - dialog fields added multiple times to the DOM

I'm using the Jquery UI to display tabs. In one of the tabs, I have a dialog box. If I navigate to that tab, open the dialog, close it, navigate off the tab then back again and open the dialog, I end up with multiple and duplicate HTML elements in the DOM.

In other words...

I've got my main page setup with tabs:

<div id="groupTabs" style="width:600px; height:600px; display:none">
    <ul>
       <li><a href="tab1.aspx"><span>Info</span></a></li>
       <li><a href="tab2.aspx"><span>Associations</span></a></li>
    </ul>
</div>

Tab #2 contains a dialog box:

<div id="dgEvent">
    <input id="someId">
</div>

...

$("#dgEvent").dialog();

I've found that if I open the dialog, navigate away (to another tab) and back again, the next time I open up the dialog I'll end up with duplicate elements both named "someId" in my DOM. This causes problems because when I try to grab the value from someID (i.e, $("#someID").val(), I end up getting the value from the first instance of the dialog.)

Is there a fix to make sure that the fields are removed when the dialog is closed? Or better yet, that they are removed properly when navigating to another tab?

EDIT

In the end, I believe the problem is related to the use of Tabs and Dialog together. Any field I have on the form that is outside the dialog gets removed from the DOM when I navigate off the tab. However, anything that was in the dialog remains in the DOM after I navigate away. Thus, when I navigate back, I end up with duplicates.

like image 895
bugfixr Avatar asked Jan 19 '11 20:01

bugfixr


3 Answers

Use

$('#your-dialog').dialog('destroy').remove();

Destroy the dialog and then remove the div with it's children from the DOM with remove().

Regards.

like image 88
Matija Grcic Avatar answered Sep 28 '22 01:09

Matija Grcic


I had similar experience.
My problem was caused by having a popup <div> inside a updatepanel.
After a ajax call, a new duplicate is created.
To solve this problem, just avoid putting the popup <div> inside an updatepanel.
Instead, put the updatepanel inside the popup <div>.
Hope it helps.

like image 27
Ike Avatar answered Sep 28 '22 03:09

Ike


Instead of $("#dgEvent").dialog();, try creating the dialog so that it doesn't auto-open, then use open and close to show/hide the dialog:

$("#dgEvent").dialog({ autoOpen: false });
$("#dgEvent").dialog('open');
$("#dgEvent").dialog('close');

See the overview section of the jQuery UI Dialog page, which references this blog post.

like image 44
Jeff Ogata Avatar answered Sep 28 '22 03:09

Jeff Ogata