我有一个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);
我创建了一个jQuery函数,以便使这个任务更容易一些。只需添加到你的JavaScript文件:
$.fn.dialogButtons = function(name, state){
var buttons = $(this).next('div').find('button');
if(!name)return buttons;
return buttons.each(function(){
var text = $(this).text();
if(text==name && state=='disabled') {$(this).attr('disabled',true).addClass('ui-state-disabled');return this;}
if(text==name && state=='enabled') {$(this).attr('disabled',false).removeClass('ui-state-disabled');return this;}
if(text==name){return this;}
if(name=='disabled'){$(this).attr('disabled',true).addClass('ui-state-disabled');return buttons;}
if(name=='enabled'){$(this).attr('disabled',false).removeClass('ui-state-disabled');return buttons;}
});};
使用类'dialog'禁用对话框中的'OK'按钮:
$('.dialog').dialogButtons('Ok', 'disabled');
启用所有按钮:
$('.dialog').dialogButtons('enabled');
启用“关闭”按钮并更改颜色:
$('.dialog').dialogButtons('Close', 'enabled').css('color','red');
我希望这能有所帮助。
我发现了一个变通方法,可能适用于试图做类似事情的人。我没有禁用按钮,而是在函数中添加了一个简单的if语句来检查复选框是否被选中。
如果不是,它会显示一条简单的消息,说在提交之前必须勾选复选框。
例如:
$("#confirmation-dialog").dialog({
modal: true,
autoOpen: false,
width: 600,
overlay: {
backgroundColor: '#000',
opacity: 0.5
},
close: function() {
$('input[type="submit"]')
.val('Record Reading')
.attr('disabled', false);
},
buttons: {
'Confirm Reading': function() {
if($('#check-box').attr("checked")){
$(this).dialog('close')
$('form')
.addClass('confirmed')
.submit();
}
else {
$('#please-check').show("slide");
}
}
}
});
不管怎样,我希望这能帮助到一些人。