2

When using jQuery UI the buttons for a modal can be set-up after init like so:

$( ".selector" ).dialog( "option", "buttons", { "Ok": function() { $(this).dialog("close"); } } );

However what I'd like to do is add multiple buttons, dependent on logic conditions:

if ( canClose ){
    $( ".selector" ).dialog( "option", "buttons", { "Ok": function() { $(this).dialog("close"); } } );
}

if ( canAlert ){
    $( ".selector" ).dialog( "option", "buttons", { "Ok": function() { alert('Hello'); } } );
}

However the above code won't work correctly, as it resets the buttons array each time.

How can I add X number of buttons using logic, without loosing any existing buttons?

3 Answers 3

3

Try it like this:

var buttons = {};

if (canClose) {
     buttons.Close = function() { $(this).dialog("close"); }
}

if (canAlert) {
    buttons.Alert = function() { alert('Hello'); }
}

$(".selector" ).dialog( "option", "buttons", buttons );

Thus you only create the dialog once. Of course, the buttons need two different names, otherwise the second one will overwrite the first one. But then, not having several buttons with the same text, that's just good GUI design. ;)

Sign up to request clarification or add additional context in comments.

Comments

1

Use the buttons array option to create both buttons:

if ( canClose && canAlert )
    $( ".selector" ).dialog( "option", "buttons", [
        {
            text: "Ok",
            click: function() { $(this).dialog("close"); }
        },
        {
            text: "Ok",
            click: function() { alert('Hello'); }
        }
    ] );

1 Comment

@Josiah-Ruddell I'm after code that would allow all four possible button combinations through logic. Either no buttons, one button, the other button or both.
1

I've managed to achieve my aim by creating an array upfront, then assigning this to the modal buttons property:

var buttons = new Array();

if ( occurance.canEdit ){
    buttons[buttons.length] = { text: "Edit", click: function(){ editOccurance(data[0],data[1]); } };
}

if ( occurance.canDelete ){
    buttons[buttons.length] = { text: "Delete", click: function(){ deleteOccurance(data[0],data[1]); } };
}

$( "#dialogOccurance" ).dialog( "option", "buttons", buttons );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.