jquery .hide() interfering with validators

68 views
Skip to first unread message

Jordan Ladora

unread,
Aug 10, 2013, 10:49:43 AM8/10/13
to web...@googlegroups.com
I have a SQLFORM.factory form that has multiple fields, one hidden by default in the view (via jquery) and shown when another field, a dropdown select, changes to some value. In the code below, field_A is shown if field_B 'Choice 2' is selected.

The problem is that fields (eg field_A) which are shown only after the dropdown is changed are not being validated properly. Here, field_B and field_C are validated just fine (they are never hidden), yet field_A is not validated in the code below - it could be anything and the form will still submit.



form = SQLFORM.factory(
    Field( 'field_A', requires=IS_IN_SET(['Choice 1', 'Choice 2'], multiple=False, zero='Please choose') ),
    Field( 'field_B', requires=IS_IN_SET(['Choice 1', 'Choice 2'], multiple=False, zero='Please choose') ),
    Field( 'field_C', requires=IS_IN_SET(['Choice 1', 'Choice 2'], multiple=False, zero='Please choose') )
)


def cvalidator(form):
    if form.vars.field_B == 'B Choice 2':
        if not form.vars.field_A: form.vars.field_A.errors = 'Fill it in'

if form.accepts(request.vars, session, onvalidation=cvalidator): pass



<script>
jQuery(document).ready(function() {

    jQuery('#no_table_field_A__row').hide();

    jQuery('#no_table_field_B').change(function(){

        if( jQuery('#no_table_field_B option:selected').text()=='Choice 2' ){
            jQuery('#no_table_field_A__row').show();
        }else{
            jQuery('#no_table_field_A__row').hide();};

    });
});
</script>

{{=form}}



How can I get all fields to validate properly here?

Thanks for help,
-j

Anthony

unread,
Aug 10, 2013, 2:31:49 PM8/10/13
to web...@googlegroups.com
field_A is validated. The problem is that when you submit the form without selecting a value for field_A, the reloaded page including the form errors initially hides field_A (including the error message below it). If you change the value of field_B and then change it again to "Choice 2", you will see field_A appear along with its error message.

Two things you probably want to do. First, assuming field_A isn't actually required unless Choice 2 is selected in field_B, you should change the field_A validator to IS_EMPTY_OR(IS_IN_SET(...)). Second, your Javascript should check whether field_B already has a value of Choice 2 (e.g., if the form is reloading with errors, and Choice 2 is already selected), and don't hide field_A in that case.

Anthony

Jordan Ladora

unread,
Aug 15, 2013, 9:09:03 PM8/15/13
to web...@googlegroups.com
Ahhhh I see - it works perfectly now - thanks very much for your help!!

-j

Reply all
Reply to author
Forward
0 new messages