views:

45

answers:

3

I jsut checked the sample of jQuery UI that opens a dialog, it's strange that the message needs to be written in HTML and read it by jQuery selector:

http://jqueryui.com/demos/dialog/

 <script>
 $(function() {
  $( "#dialog" ).dialog();
 });
 </script>



<div class="demo">

<div id="dialog" title="Basic dialog">
 <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>

What I want to do is quite simple, I want the dialog to display a string defined as a js variable, like this:

var cmd_str = "abcdefg";
$(cmd_str).dialog();

But this doesn't seem to work well.

+1  A: 

when you call $(cmd_str) jQuery searches for a tag named abcdefg... you should put the entire markup inside $(), then inject it into the DOM and then call .dialog(). Like that, I guess.

$("<div id=\"dialog\" title=\"Basic dialog\">"+
    "<p>This is the default dialog which is useful for displaying information."+
    "The dialog window can be moved, resized and closed with the 'x' icon.</p>"+
    "</div>").appendTo("body").dialog();
Minkiele
This looks like ugly, is there any better way. To display a dialog, I MUST put it into the body? This looks weird.
Bin Chen
and if I put it to body, the text will be displayed to user which is unwanted behavior.
Bin Chen
@Bin Chen I "rewrote" your example in Javascript. I never tried red-X solution, so I guess I did learn something new today :)
Minkiele
+2  A: 

It cannot be just any string, it needs to be html.

var cmd_str = "<div>abcdefg</div>";
$(cmd_str).dialog();

or maby a cleaner version:

var cmd_str = "abcdefg";
$(cmd_str).wrap("<div></div>").dialog();

Further explanation:

$("abcdefg") would match a <abcdefg /> element as $("a") would match a <a /> element.

To destroy:

Easiest would be to save the jquery object used for the dialog in a variable like this.

var cmd_str = "abcdefg";
var $message = $(cmd_str).wrap("<div></div>").dialog();

function destroyMessage(){
    $message.dialog("destroy");
}
red-X
that's great, it works!
Bin Chen
Added some explanation.
red-X
do you know how to destroy this dialog?
Bin Chen
See adition in answer.
red-X
+1  A: 

You have to have a div or some other element, make it hidden then the dialog will make it visible according to the dialogs .show and .hide functions. Use the .text or .val (depending on message element) functions to set your message.

<div id="dialogMsg" style="hidden"></div>
$("#dialogMsg").text("Your message").dialog().show();
// ... or it can be closed if settings are set when doing .dialog(...)
$("#dialogMsg").hide();
AntonioP
the $("#dialogMsg").hide(); doesn't work. It will have a title bar still there, please test it.
Bin Chen