jQuery UI dialog button text as a variable

JqueryJquery UiVariablesJquery Ui-Dialog

Jquery Problem Overview


Can anyone tell me how can i use a variable for button text in jQuery UI dialog? I want to make a dynamic button name.

Jquery Solutions


Solution 1 - Jquery

This won't work because of the way jQuery handles the button name (can be with or without quotes)

This will work:

var button_name = 'Test';
var dialog_buttons = {}; 
dialog_buttons[button_name] = function(){ closeInstanceForm(Function); }
dialog_buttons['Cancel'] = function(){ $(this).dialog('close'); }	
$('#instanceDialog').dialog({ buttons: dialog_buttons });

Solution 2 - Jquery

What you can do is assign the button in the dialog an ID and then manipulate it using standard jQuery.

$("#dialog_box").dialog({
    autoOpen: false,
    modal: true,
    resizable: false,
    buttons: [{
        text: "Ok",
        "id": "btnOk",
        click: function () {
            //okCallback();
        },

    }, {
        text: "Cancel",
        click: function () {
            //cancelCallback();
        },
    }],
    close: function () {
        //do something
    }
});

Set button text:

 var newLabel = "Updated Label";
 $("#btnOk").html('<span class="ui-button-text">'+ newLabel +'</span>')

Solution 3 - Jquery

The problem here is that the dialog plugin does not assign an id to its buttons, so it's quite difficult to modify them directly.

Instead, initialise the dialog as normal, locate the button by the text it contains and add an id. The button can then be accessed directly to change the text, formatting, enable/disable it, etc.

$("#dialog_box").dialog({
buttons: {
    'ButtonA': function() {
        //... configure the button's function
    }
});
$('.ui-dialog-buttonpane button:contains(ButtonA)').attr("id","dialog_box_send-button");			
$('#dialog_box_send-button').html('Send')		

Solution 4 - Jquery

  1. The button option in jQuery UI dialog accepts objects and arrays.
  2. The buttons are instances of the button widget. Use the API instead of manipulating the buttons yourself.

$(function() {
  // using textbox value instead of variable
  $("#dialog").dialog({
    width: 400,
    buttons: [
      { text: $("#buttonText0").val(), click: function() { $(this).dialog("close"); } }, 
      { text: $("#buttonText1").val(), click: function() { $(this).dialog("close"); } }
    ]
  });
  $("#updateButtonText").on("click", function() {
    var $buttons = $("#dialog").dialog("widget").find(".ui-dialog-buttonpane button");
    console.log($buttons.get());

    $buttons.eq(0).button("option", "label", $("#buttonText0").val());
    $buttons.eq(1).button("option", "label", $("#buttonText1").val());

    // few more things that you can do with button widget
    $buttons.eq(0).button("option", "icons", { primary: "ui-icon-check" });
    $buttons.eq(1).button("disable");

    $("#dialog").dialog("open");
  });
});

@import url("https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css");

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>

<div id="dialog" title="Sample Dialog">
  <p>Proceed?</p>
</div>

<p style="text-align: center;">
  <input type="text" id="buttonText0" value="OK">
  <input type="text" id="buttonText1" value="Cancel">
  <input type="button" id="updateButtonText" value="Update Button Text">
</p>

Solution 5 - Jquery

Maybe I'm missing the point - but wouldn't the easiest way be to use the setter?

     $("#dialog_box").dialog({
        buttons: {
         [
            text:"OK",
            click: function() {
                //... configure the button's function
            }
         ]
        });
        
        $("#dialog_box").dialog("option", "buttons", { "Close": function() { $(this).dialog("close"); } });

Solution 6 - Jquery

This will work $($("button", $("#dialogId").parent())[NUMBER_OF_YOUR_BUTTON]).text("My Text");

Solution 7 - Jquery

And don't forget

$($("button", $(".info_dialog").parent())[1]).html("<span class='ui-button-text'>Button text here.</span>");

Solution 8 - Jquery

This can be done in following steps :

  1. In JavaScript you can create Array of Buttons.
  2. Set buttons property to the Array of Buttons.

Following Example explains above steps.

  1. Two buttons are defined in btnArray as follows;

> var btnArray = [ > { text: "Add Entry", > click: function(){ > this.retVal = true; > addRowIntoTemplateManifest(); > $(this).dialog('close'); > } > }, > { text: "Cancel", > click: function(){ > this.retVal = false; > $(this).dialog('close'); > } > } > ];

A custom function displayConfirmDialog_Dynamic() is written that accpets, Dialog header, Dialog Text, button Array. The call to this function is as follows:

displayConfirmDialog_Dynamic("Add Template Manifest Entry?", "Do you want to add following Cuboid Entry to Template Manifest?\nCuboidNane: '" + json.cuboidName + "' CuboidId: " + json.cuboidId + "\non Server:"
+ json.serverUrl , btnArray );

The function displayConfirmDialog_Dynamic is as follows:

//Confirmation dialog Dynamic Buttons
function displayConfirmDialog_Dynamic(dlgTitle, message, btnArray)
{
    var retVal;
    $("div#dialog-confirm").find("p").html(message);

    var confirmDlg = $( "#dialog-confirm" ).dialog({
          resizable: false,
          height: "auto",
          width: 400,
          modal: true,
          title: dlgTitle,
          buttons: btnArray,
          show:{effect:'scale', duration: 700},
          hide:{effect:'explode', duration: 700}  
    });

    confirmDlg.dialog('option', 'buttons', btnArray);
    confirmDlg.prev(".ui-dialog-titlebar").css({"background":"#ffc000", "color":"#ffffff", "font-size":"13px", "font-weight":"normal"}) ;
    confirmDlg.dialog("open");  
}

The Confirm Dialog Template is defined as DIV tag as follows. Note that the title and contents of <p> tag are changed dynamically by JavaScript code.

<div id="dialog-confirm" title="Empty the recycle bin?" style="display:none;">
  <p>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>

The Screenshot of dialog box displayed by above code is shown below:

enter image description here

Solution 9 - Jquery

var buttonName = "something";
$('#button-id').attr('value', buttonName);

Solution 10 - Jquery

assign a class to the button. The button text will be in a span with a class called ui-button-text inside your defined class. So if you give your button the class .contacts-dialog-search-button then the code to access the text will be:

$('.ui-button-text','.contacts-dialog-search-button').text();

here is the code I'm using for my current projects buttons, to give you an example.

buttons : [
			{
				text : 'Advanced Search',
				click : function(){
					if($(this).dialog("option", "width")==290){
						$('#contacts-dialog-search').show();
						$(this).dialog("option", "width", 580);
						$('.ui-button-text','.contacts-dialog-search-button').text('Close Search');
					}
					else{
						$('#contacts-dialog-search').hide();
						$(this).dialog("option", "width", 290);
						$('.ui-button-text','.contacts-dialog-search-button').text('Advanced Search');
					}
				},
				"class" : "contacts-dialog-search-button"
			}
    		]

Solution 11 - Jquery

Yes completely possible with inline behaviour:

  1. Create Dialog class with two setter method, setYesButtonName() and setNoButtonName.

        function ConfirmDialog() {
            var yesButtonName = "Yes";
            var noButtonName = "No";
            this.showMessage = function(message, callback, argument) {
                var $dialog = $('<div></div>')
                    .html(message)
                    .dialog({
                        modal: true,
                        closeOnEscape: true,
                        buttons: [
                            {
                                text:yesButtonName,
                                click: function() {
                                    if (callback && typeof(callback) === "function") {
                                        if (argument == 'undefined') {
                                            callback();
                                        } else {
                                            callback(argument);
                                        }
                                    } else {
                                        $(this).dialog("close");
                                    }
                                }
                            },
                            {
                                text:noButtonName,
                                click: function() {
                                    $(this).dialog("close");
                                }

                            }
                        ]
                    });
                $dialog.dialog("open");
            };

            this.setYesButtonName = function(name) {
                yesButtonName = name;
                return this;
            };

            this.setNoButtonName = function(name) {
                noButtonName = name;
                return this;
            };
        }

  1. Create Object of ConfirmDialog class.

      this.CONFIRM_DIALOG = new ConfirmDialog();
    
  2. Call method on any event, let's say onclick()

     OK_DIALOG.setYesButtonName('Wana Marry').showMessage('Worst Idea!!');
    

Job Done!!

Solution 12 - Jquery

why not a one liner...

$("span.ui-button-text:contains('OLD BUTTON NAME')").html('NEW BUTTON NAME');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNishimaView Question on Stackoverflow
Solution 1 - JqueryW. van KuipersView Answer on Stackoverflow
Solution 2 - JquerycrabCRUSHERclamCOLLECTORView Answer on Stackoverflow
Solution 3 - JqueryDavid ToyView Answer on Stackoverflow
Solution 4 - JquerySalman AView Answer on Stackoverflow
Solution 5 - JqueryDannyView Answer on Stackoverflow
Solution 6 - JqueryEgor PavlikhinView Answer on Stackoverflow
Solution 7 - JqueryAndrewView Answer on Stackoverflow
Solution 8 - JqueryRahul VaradkarView Answer on Stackoverflow
Solution 9 - JqueryJeff OberView Answer on Stackoverflow
Solution 10 - JqueryDaithíView Answer on Stackoverflow
Solution 11 - JqueryAshView Answer on Stackoverflow
Solution 12 - JqueryTrefforView Answer on Stackoverflow