variable amount of optional parameters

51 Views Asked by At

Im using this tool here http://craftpip.github.io/jquery-confirm/#dialog and i wanted to have a popup that has a variable amount of buttons based on a piece of data used to construct pop up.

Here is an example of what a very simple/empty one looks like.

$.confirm({
    title: 'testing',
    content: 'this has two static buttons',
    buttons: {
        confirm: function () {
        },
        cancel: function () {
        },
    }
});

What i want is to be able to put a foreach loop in side of "buttons: { ... }".

Is there a way to do so or a way to achieve what i am trying to do?

2

There are 2 best solutions below

1
On

Just build your options object before :

var options = {
    title: 'testing',
    content: 'this has two static buttons',
    buttons: {},
};

$.each( variable_name, function(){
    options.buttons[ this.btn_name ] = this.fn;
} );

$.confirm( options );

Of course, everything depends on how the object you loop looks like, but the logic is here.

1
On

Your logic is inverted. The following is an object:

{
    title: 'testing',
    content: 'this has two static buttons',
    buttons: {
        confirm: function () {
        },
        cancel: function () {
        },
    }
}

So you could do:

var options = {
    title: 'testing',
    content: 'this has two static buttons',
    buttons: {
        confirm: function () {
        },
        cancel: function () {
        },
    }
};
$.confirm(options);

You then can add items by

options.buttons["mybutton"] = function() { };

You can place the previous code in a loop and change the string "mybutton" to whatever you want for whatever functions you have. You're basically asking how to add a property to and existing javascript object.