How to find all dialogs in JQuery
Asked Answered
S

2

6

I am trying to bind an event to all dialogs that have been created on a page using the JQuery UI Dialog function (whether they have been displayed or not). I can't seem to figure out a selector that will get me there. I've tried both .ui-dialog and .ui-dialog-content without success.

Since I'm trying to make a generic method, I won't know the IDs of the dialogs that may have been created.

I'm using the following code to test. It works if I specify a dialog's id (#mydialog), but in production, I won't know these.

$("div.ui-dialog").bind("dialogclose", function(event, ui) {
  window.alert("close fired");
}
Sullage answered 12/3, 2011 at 19:58 Comment(0)
T
8

Do your dialogs have a common class that you can select them with? If they all have the "ui-dialog" class then this will work:

$(".ui-dialog")

Your example of

$("div.ui-dialog")

Is asking to select all divs with a class of ui-dialog, which should probably also work as long as the class is given to a div element.

Your problem might be that you binding the dialog elements before they exist? You might want the .live() function instead so that it binds to any dialogs created at any point and not just the ones that exist when the function is called.

Posting an HTML snippet would help.

Tasha answered 12/3, 2011 at 21:8 Comment(1)
changing the call to .live() solved the problem (and a couple of others in my app!) For future reference, the ui-dialog class is added by JQuery UI, so the code above, with the change to live() instead of bind() is generic and should work anywhere.Sullage
A
3

You can use this:

$(":ui-dialog").each(function(){
   "enter your code here"
})
Abstinence answered 18/7, 2012 at 17:22 Comment(2)
I don't know because for me ".ui-dialog" don't run, but only ":ui-dialog"Abstinence
This works great. Selecting by class should usualy work, but there's no guarantee that only dialogs are used. This is a jQuery-meta-selector, (like :visible), which is pretty much guaranteed to get all dialogs and nothing else.Lepidopterous

© 2022 - 2024 — McMap. All rights reserved.