views:

31

answers:

2

I have a JavaScript function that I'm passing an argument to, that opens a jQueryUI Dialog. I want the dialog to have either one or two buttons, based on the value of the argument. How should I do this?

So far I've tried:

function foo(hasFile) {
    $('#dialog').dialog({
        buttons: {
            Close: function() { $(this).dialog('close'); },
            if (hasFile)
                "Download": // do something
    }
    });
}

and

function foo(hasFile) {
    $('#dialog').dialog({
        buttons: 
            if (hasFile)
            {
                "Download": // do something
                Close: function() { $(this).dialog('close'); }
            }
            else
            {
                Close: function() { $(this).dialog('close'); }
            }
    });
}

both of which have thoroughly broken my page.

+1  A: 

buttons is a JavaScript literal object. You could do something like this:

function foo(hasFile) {
    var buttons = {
        Close: function() { $(this).dialog('close'); }
    };

    if (hasFile) {
        buttons.Download = function(){
            // Do something.
        };
    }
    $('#dialog').dialog({
        buttons: buttons
    });
}
CalebD
Thank you, that works perfectly. One more question - I need the button to have the text of "Download PPT". Setting a var btn = "Download PPT" and doing buttons.btn = function() {} has not worked - any suggestions?
jawonlee
Never mind, I got it - it's buttons["Download PPT"]
jawonlee
+1  A: 

A general way to do that is like this:

foo.dialog({
  // ...
  buttons: (function() {
    function CloseHandler() {
      // close ...
    };
    function DownloadHandler() {
      // download ...
    };

    return condition ?
      { "Download": DownloadHandler, "Close": CloseHandler } :
      { "Close": CloseHandler };
  })(),
  // ...
});

The idea is that you create a function where you can make decisions, and then return the result you decide upon.

Pointy