我有一个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');
}
}
})
});
如果你创建一个对话框,为按钮提供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);
您需要设置disabled属性
$('#continueButton').attr("disabled", true);
更新:啊哈,我现在看到复杂性了。jQuery对话框中有一行是有用的(在“按钮”部分下)。
var buttons = $('.selector').dialog('option', 'buttons');
您需要从对话框中获取按钮集合,循环查找您需要的按钮,然后设置如上所示的disabled属性。
我希望能够通过名称找到按钮(因为我有几个按钮在我的jQuery UI对话框)。我在页面上也有几个对话框,所以我需要一种方法来获得特定对话框的按钮。这是我的函数:
function getDialogButton( dialog_selector, button_name )
{
var buttons = $( dialog_selector + ' .ui-dialog-buttonpane button' );
for ( var i = 0; i < buttons.length; ++i )
{
var jButton = $( buttons[i] );
if ( jButton.text() == button_name )
{
return jButton;
}
}
return null;
}
// create the dialog
$('#my_dialog').dialog( dialogClass : 'dialog1',
buttons: {
Cancel: function() { $(this).dialog('close'); },
Submit: function() { ... }
} );
// now programmatically get the submit button and disable it
var button = getDialogButton( '.dialog1', 'Submit' );
if ( button )
{
button.attr('disabled', 'disabled' ).addClass( 'ui-state-disabled' );
}
调用。attr("disabled", true)当然有效,但使用jQuery你想做更多的'糖'方式,所以我写了一个简单的扩展:
(function( $ ) {
$.fn.disable = function(isDisabled) {
var val = isDisabled;
if (isDisabled === undefined)
val = true;
this.attr("disabled", val);
};
$.fn.enable = function(isEnabled) {
var val = !isEnabled;
if (isEnabled === undefined)
val = false;
this.attr("disabled", val);
}
})( jQuery );
现在你有了函数enable()和disable(),所以你可以这样做:
$('#continueButton').disable();
这和
$('#continueButton').disable(true);
and
$('#continueButton').enable(false);