rharper
rharper

Reputation: 565

Flask WTForms disabling multiple fields with multiple buttons

I have a form in Flask made with WTForms. It includes 3 checkboxes, and 9 other fields. 7 of those fields are disabled if one out of the three checkboxes are ticked.

Here is just a small sample of a checkbox, a field that is disabled when the checkbox is ticked, and also the OptionalIf class that makes the selected field optional if the checkbox is ticked:

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)

Inside my form class:

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')])

The holiday_noAddedHours and sick are the other checkbox fields, that each have their own ID: holidayNAH and sick.

As there are seven fields to be disabled, I have to have this within my scripts:

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;
  ....
}

And then another one for the sick ID.

I was wondering if it was possible to shorten this, instead of having 3 document.getElementByIds and seven lines within that disabling the fields if the box is checked? I understand that having one ID is not possible as it getElementById gets the first element, so how would I go about this?

Thanks for any advice.

Upvotes: 1

Views: 761

Answers (1)

smallpants
smallpants

Reputation: 490

How about a for loop over a list of the id's you want to change. For example:

all_ids = ['timepick1', 'timepick2'];


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

Upvotes: 1

Related Questions