我有一个jQuery对话框,要求用户输入某些信息。在这个表单中,我有一个“continue”按钮。我想这个“继续”按钮只被启用一旦所有的领域有内容在他们,否则它将保持禁用。
我写了一个函数,每当字段状态发生变化时就调用它。但是,我不知道如何从这个功能启用和禁用对话框按钮。我该怎么办?
哎呀,我忘了说这些按钮是这样创建的:
$(function() {
$("#dialog").dialog({
bgiframe: true,
height: 'auto',
width: 700,
show: 'clip',
hide: 'clip',
modal: true,
buttons: {
'Add to request list': function() {
$(this).dialog('close');
$('form').submit();
},
'Cancel': function() {
$(this).dialog('close');
}
}
})
});
根据文档:
https://api.jqueryui.com/dialog/#option-buttons
// Setter
$( ".selector" ).button( "option", "disabled", true );
为了能够简单地选择按钮,你可以为按钮添加一个自己的CSS类,它应该是启用/禁用的。
// while initializing
$("#dialog").dialog({
...
buttons: [{
disabled: true,
text: "Add to request list",
click: function (e: JQueryEventObject) {
// Some logic
},
"class": "myDialogButton"
}]
...
});
然后启用/禁用看起来像这样:
$(".myDialogButton" ).button( "option", "disabled", (SOME_CONDITION) ? true : false);
不幸的是,这里给出的解决方案对页面上的几个对话框都不起作用。
同样的问题是,原来的对话框本身不包含按钮窗格,但它是一个兄弟。
我想到了通过对话框ID进行选择
var getFirstDialogButton = function (dialogSelector) {
return $('.ui-dialog-buttonpane button:first',
$(dialogSelector).parent()[0]);
};
...
$('#my_dialog').dialog({
open: function(event, ui) {
getFirstDialogButton("#my_dialog")
.addClass("ui-state-disabled").attr('disabled', 'disabled' );
},
...
然后同样的getFirstDialogButton()函数可以稍后用于启用按钮,例如在成功验证之后。
希望它能帮助到一些人。
你把一件简单的工作复杂化了;jQueryUI对话框有两种方法来设置按钮。
如果您只需要为每个按钮设置单击处理程序,请使用带有Object参数的选项。要禁用按钮和提供其他属性,请使用接受Array参数的选项。
下面的示例将禁用一个按钮,并通过应用所有jQueryUI CSS类和属性来正确更新其状态。
步骤1 -创建一个按钮数组对话框:
// Create a dialog with two buttons; "Done" and "Cancel".
$(".selector").dialog({ buttons: [
{
id: "done"
text: "Done",
click: function() { ... }
},
{
id: "cancel"
text: "Cancel",
click: function() { ... }
}
] });
步骤2 -在对话框创建后启用/禁用Done按钮:
// Get the dialog buttons.
var dialogButtons = $( ".selector" ).dialog("option", "buttons");
// Find and disable the "Done" button.
$.each(buttons, function (buttonIndex, button) {
if (button.id === "done") {
button.disabled = true;
}
})
// Update the dialog buttons.
$(".selector").dialog("option", "buttons", dialogButtons);
如果你创建一个对话框,为按钮提供id,
$("#dialog").dialog({ buttons: [ {
id: "dialogSave",
text: "Save",
click: function() { $(this).dialog("close"); }
},
{
id: "dialogCancel",
text: "Cancel",
click: function() { $(this).dialog("close");
}
}]});
我们可以用下面的代码禁用按钮:
$("#dialogSave").button("option", "disabled", true);
下面是修改后的问题示例,一旦点击就会禁用按钮:
$(function() {
$("#dialog").dialog({
bgiframe: true,
height: 'auto',
width: 700,
show: 'clip',
hide: 'clip',
modal: true,
buttons: {
'Add to request list': function(evt) {
// get DOM element for button
var buttonDomElement = evt.target;
// Disable the button
$(buttonDomElement).attr('disabled', true);
$('form').submit();
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
}
另外,下面的问题也会有帮助:
如何禁用jQuery UI对话框上的按钮?