【问题标题】:Flask WTForms disabling multiple fields with multiple buttonsFlask WTForms 使用多个按钮禁用多个字段
【发布时间】: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_noAddedHourssick 是其他复选框字段,每个字段都有自己的 ID:holidayNAHsick

由于有七个字段要禁用,我必须在我的脚本中包含这个:

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


    【解决方案1】:

    如何对要更改的 id 列表进行 for 循环。例如:

    all_ids = ['timepick1', 'timepick2'];
    
    
    for (i=0; i<all_ids.length; i++){
        document.getElementById(all_ids[i]).disabled = this.checked;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-05
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多