【发布时间】:2019-05-10 23:29:11
【问题描述】:
我有一个用 WTForms 制作的 Flask 表单。它包括 3 个复选框和 9 个其他字段。如果勾选了三个复选框中的一个,其中 7 个字段将被禁用。
这里只是一个复选框的一个小示例,一个在选中复选框时禁用的字段,还有一个 OptionalIf 类,如果选中复选框,则使所选字段成为可选:
class OptionalIf(Optional):
def __init__(self, otherFieldName, *args, **kwargs):
self.otherFieldName = otherFieldName
#self.value = value
super(OptionalIf, self).__init__(*args, **kwargs)
def __call__(self, form, field):
otherField = form._fields.get(self.otherFieldName)
if otherField is None:
raise Exception('no field named "%s" in form' % self.otherFieldName)
if bool(otherField.data):
super(OptionalIf, self).__call__(form, field)
在我的表单类中:
holiday = BooleanField('Holiday?', id="holiday", validators=[Optional()])
start_time = TimeField(label='Start Time', id='timepick1', format='%H:%M', validators=[OptionalIf('holiday'), OptionalIf('holiday_noAddedHours'), OptionalIf('sick')])
holiday_noAddedHours 和 sick 是其他复选框字段,每个字段都有自己的 ID:holidayNAH 和 sick。
由于有七个字段要禁用,我必须在我的脚本中包含这个:
document.getElementById('holiday').onchange = function(){
document.getElementById('timepick1').disabled = this.checked;
document.getElementById('timepick2').disabled = this.checked;
....
}
document.getElementById('holidayNAH').onchange = function(){
document.getElementById('timepick1').disabled = this.checked;
document.getElementById('timepick2').disabled = this.checked;
....
}
然后是sick ID 的另一个。
我想知道是否可以缩短它,而不是在选中该框时禁用 3 个document.getElementByIds 和七行?我知道拥有一个 ID 是不可能的,因为它 getElementById 获取第一个元素,那么我该怎么做呢?
感谢您的建议。
【问题讨论】:
标签: javascript python flask wtforms