2012-05-28 10 views
9

Tengo un modal jQuery en el que deseo agregar un botón adicional si se cumple una declaración condicional.Botón condicional agregado a jQuery modal

Código original de la muestra (disección):

$("#dialog").html("<div></div>").dialog({ 
    title: "Some Title", 
    modal: true, 
    width: 550, 
    buttons: { 
     Ok: function() { 
      // 
     }, 
     'A Button': function() { 
      // 
     } 
    } 
}).dialog('open'); 

Así como se ve arriba hay un modal con 2 botones, pero también desea agregar allí algo de código dinámico para poder atender a un adicional botón si se establece una variable. p.ej.

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'); 

Respuesta

16

Se puede crear el objeto buttons antes de crear el diálogo:

//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 
}); 
3

Como alternativa, puede crear todos los botones que necesitas y luego mostrar u ocultar ellos en función del caso, y en función de lo que sucede en su diálogo. Una de las formas de hacerlo es usar el evento de creación de diálogo jqueryui.

Se puede hacer referencia a un ejemplo de trabajo en: 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"); 
    } 
}); 
Cuestiones relacionadas