I have a jQuery modal where I want to add an additional button if a conditional statement is met.
Original sample code (cutdown):
$("#dialog").html("<div></div>").dialog({
title: "Some Title",
modal: true,
width: 550,
buttons: {
Ok: function() {
//
},
'A Button': function() {
//
}
}
}).dialog('open');
So as you see above there is a modal with 2 buttons, but I also want to add in there some dynamic code to be able to cater for an additional button if a variable is set. e.g.
var some_variable = 0;
$("#dialog").html("<div></div>").dialog({
title: "Some Title",
modal: true,
width: 550,
buttons: {
Ok: function() {
//
},
'A Button': function() {
//
}
/* ??? */
if (some_variable==1) //then add the other button's code here..
/* ??? */
}
}).dialog('open');
You could create the buttons
object before creating the dialog:
//Create the buttons object
var buttons = {
Ok: function() {},
'A Button': function() {}
};
//Add another button to that object if some condition is true
if(something) {
buttons['B button'] = function() {};
}
//Create the dialog, passing in the existing buttons object
$("#dialog").html("<div></div>").dialog({
buttons: buttons,
//Other options
});
Currently there's no way to modify just one button, but you can reset the full button hash using the option method:
if your condition meets then reset buttons again.
$('#contactform').dialog('option', 'buttons', {...});
http://old.nabble.com/jQuery-dialog-add-remove-button-on-the-fly-td22036498s27240.html
Alternatively, you can create all the buttons you need and then display or hide them depending the case, and depending what happens in your dialog. One such way to do so is using the jqueryui dialog create event.
You can refer to a working example at: http://jsfiddle.net/eCLuy/
$("#dialog").dialog({ buttons: { 'prev': { text: 'prev', id: "prevB", click: function() { $(this).closest(".ui-dialog").find(".ui-button#prevB").addClass("hidden"); $(this).closest(".ui-dialog").find(".ui-button#nextB").removeClass("hidden"); } }, 'next': { text: 'next', id: "nextB", click: function() { $(this).closest(".ui-dialog").find(".ui-button#prevB").removeClass("hidden"); $(this).closest(".ui-dialog").find(".ui-button#nextB").addClass("hidden"); } } }, // http://api.jqueryui.com/dialog/#event-create // Triggered when the dialog is created. // Initialize the dialog with the create callback create:function () { $(this).closest(".ui-dialog").find(".ui-button#prevB").addClass("hidden"); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With