jQuery UI dialog buttons - defining function with variables

37 Views Asked by At

My site is using a confirmation dialog, for which I'm using a jQuery UI Dialog.

I'm trying to add my own buttons, based on reading values from various divs. The problem I'm having is that, while I can get the text to read in ok, I can't get the click function to use the values that I read in.

Here's what I'm doing:

The confirmation dialog HTML:

<div class="dialogConfirm"
     numbuttons="2" 
     button0="Delete entirely" 
     button1="Delete from Main site only" 
     value0="-1" 
     value1="1">
    <p class="dialogConfirmMessage">Do you wish to remove this slide from all sites on which it appears, or just from the Main site?</p>
</div>

(So the buttons which are shown should be 'Delete entirely' and 'Delete from main site only'. The values of the buttons should be -1 and 1 respectively)

Define initial dialog:

$( ".dialogConfirm" ).dialog({
        autoOpen: false,        // wait until an appropriate link is clicked
        height: "auto",         // set height and width automatically
        width: "auto",
        modal: true             // other items on page are disabled
    });

Add the custom buttons:

$('.dialogConfirm').each(function() {
    var buttonsArray = [];
    var arrayLength = $(this).attr('numButtons');
    for(var ii=0; ii<arrayLength; ii++) {
        var button = $(this).attr('button' + ii);
        var value = $(this).attr('value' + ii);
        var thisButton = {
            text: button,
            click: function() {
                    call_function(value);
            }
        }
        buttonsArray.push(thisButton);
    }
    $( this ).dialog("option", "buttons", buttonsArray);
});

So, when the first button is clicked, I want to call 'call_function', passing in the value '-1'. When the second button is clicked, I want to call 'call_function', passing in the value 1.

The problem is that 'call_function' is always called with the most recently-set value of 'value', ie 1 (I've tried changing the values etc to check, and it's definitely that it's using the most recent value).

So it's setting the function correctly, but leaving 'value' as a variable, instead of passing it in as a set number; it then evaluates 'value' when the button is clicked.

0

There are 0 best solutions below