Unable to use dynamic text for button name in jQuery UI dialog

I’ve the following working JSFiddle with the dialog and some textual buttons.

Can someone explain me why can’t I replace the following line "Login next suggested value": function() { with something like "Login next suggested value "+additionalValue+"" ? I want to have the name of the button display Login next suggested value ABC1234 such that I can have ABC1234 as dynamic field but the the replacement I tried above doesn’t work in case of buttons.

You can’t use variables in the key when defining an object literal. Define your buttons as a variable, and pass that in the configuration instead of defining them inline.

const buttons={};
buttons["Login next suggested value "+additionalValue]=function(){...};
buttons["Cancel button"]=function(){...};

$( "#dialog-confirm" ).dialog({
      ...,
      buttons: buttons
});

You can define the buttons object separately, and then use it in the dialog. This way, you can set dynamic properties (i.e., button names) for the object

Here is how

let additionalValue = "ABC12345";

console.log("Login next suggested value " + additionalValue + "");

let buttons = {};

// Use bracket notation to set a dynamic property key for the object
buttons["Login next suggested value " + additionalValue] = function() {
    $(this).dialog("close");
};
buttons["Cancel button"] = function() {
    $(this).dialog("close");
};

$("#dialog-confirm").dialog({
    resizable: false,
    height: "auto",
    width: 400,
    modal: true,
    buttons: buttons
});

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.