简体   繁体   中英

Hide/show multiple WTForm labels

How can I hide/show multiple wtform labels. Currently I am doing this.

HTML:

 {{ render_field(var_1, class = "class_1") }}
 {{ render_field(var_2, class = "class_1") }}
 {{ render_field(var_3, class = "class_1") }}

JQuery:

    $('label[for="var_1"]').show();
    $('label[for="var_2"]').show();
    $('label[for="var_3"]').show();

Is there a better way? For example assigning a class to the labels?

Thank You!

If you want to show or hide a field for some specific reason, you have to do two things. First show the fields that you want and hide the fields that you don't want. It could be done using jquery and css.

$("any id or class").click(function(){
$('#parent_div_of_field_id_that_you_want_to_show').css('display','block');
$('#parent_div_of_field_id_that_you_want_to_show').attr('data-parsley-required','false') //if you are using parsley for client side validation
$('#parent_div_of_field_id_that_you_want_to_hide').css('display','none');
$('#parent_div_of_field_id_that_you_want_to_hide').attr('data-parsley-required','true') //if you are using parsley for client side validation

Now you have to handle the server side validation. You have to stop the validation of those hidden fields. To do this use StopValidation for wtforms.

from wtforms.validators import StopValidation
def functionName(form, field):
    if form.your_field_name.data==None:
        field.errors[:] = []
        raise StopValidation()

And this function like this

name=StringField("Name",  [functionName, validators.DataRequired("Name is required")])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM