1
votes

I have a task for WordPress website which use Contact Form 7 plugin.

How do I set textarea as required only if value of another field ( [number* number-265 min:0 id:antala] ) > 0 ?

So, it should be not like [textarea* stelnummera id:stelnummera] because this textarea will be required every time.

I have created javascript code which add some classes, attributes and alert message (how it add Contact Form 7 plugin):

    $( "#antala" ).change(function() {
        if ( $( "#antala" ).val() > 0 ) {
            $( "#stelnummera" ).addClass( "wpcf7-validates-as-required wpcf7-not-valid" ).attr( "aria-required", "true" ).attr( "aria-invalid", "true" );
        } else {
            $( "#stelnummera" ).removeClass( "wpcf7-validates-as-required wpcf7-not-valid" ).attr( "aria-required", "false" ).attr( "aria-invalid", "false" );
        }
    });

    $( ".wpcf7-form" ).submit(function( event ) {

        if ( $( "#antala" ).val() > 0 && $( "#stelnummera" ).val() == "" ) {
            event.preventDefault();
            $( "#stelnummera" ).attr( "aria-invalid", "true" );
            $( "#stelnummera" ).after( "<span class='custom-alert' style='color: #f00;'>Dette felt skal udfyldes</span>" );
            if ($ ( ".invalid" ).length == 0 ) {
                $ ( ".wpcf7-form" ).addClass( "invalid" );
            }
        } else {
            $( "#stelnummera" ).attr( "aria-invalid", "false" );
            $( ".custom-alert" ).remove();
        }

    });

But the form still submitting

1
Why are you evaluating for > 0 if you want to check for > 1? Also, you should convert string .val()s to integers. - rnevius
I'm sorry, this is my typo. - Z. Dmitry

1 Answers

0
votes

I have just hide this textarea until value of number field will be > 0.

Textarea is required [textarea* stelnummera id:stelnummera]

    $("#stelnummera").parent().parent().hide();
    $("#stelnummera").val('n/a');

    $("#antala").change(function() {
        if ($("#antala").val() > 0) {
            $("#stelnummera").parent().parent().show();
            $("#stelnummera").val('');
        } else {
            $("#stelnummera").parent().parent().hide();
            $("#stelnummera").val('n/a');
        }
    });