简体   繁体   中英

Pre-validating form before submitting

I am trying to make something display (or not display depending on what they choose). But, I need to do that BEFORE validation. How could I do this? My code does that only AFTER pressing the submit button. But I need to pre-validate it, so that the colour red appears from the get go.

(note: I don't wanna use hardcoded CSS, since I need to use a similar code for display and display none).

if($('#amortization_years').val() == '' || $('#amortization_years').val() == 0 || $('#amortization_years').val() >= 36 || $('#amortization_months').val() >= 12 || ($('#amortization_years').val() == 35  && $('#amortization_months').val() > 0))

{
    $('#amortization_years').css('border', 'solid red 2px');
    $('#error_years').fadeIn(3000);
    $('#amortization_months').css('border', 'solid red 2px');
    $('#error_months').fadeIn(3000);
    valid = false;}
    else {($('#error_years').fadeOut(3000) && $('#error_month').fadeOut(3000));
}

EDIT: reworked but still need help

I worked on the content that @Aprillion linked me to. This is what I sort of need (reworked), which is for a dropdown menu.

In the end, there is a portion of the form (#16 from the dropdown menu) which NEEDS to appear ONLY if certain conditions are met (basically where if a person chooses the 1st answer, only then could he also pick the 16th question, which would appear inside the dropdown menu. So basically, if the person does NOT pick any item in the dropdown menu which contains 15 items (plus the 16th one), then he could NOT pick #16.

Here is the code I was reworking.

    <script>
            /*
The id for the thing
    sCat-<?php echo $numProj; ?><?php echo $numC ?>
    */
    window.onload=function(){
        var validate = function(evt){
            // your custom code, e.g.:
            valid = true;
            if ($('.16th').val() !== "sCat-<?php echo $numProj; ?><?php echo $numC ?>") {
                //valid = false;
                $('.16thup').css('display', 'none');
                //$('#a').addClass("invalid");
            } else {
                //$('#a').removeClass("invalid");
                $('.16thup').css('display', 'block');
            }
            //return valid;
        }

        $('#myform').change(validate);
        $('#myform').submit(validate);
        }

    </script>

You can bind the validation to the change event as well as to submit .

http://api.jquery.com/change/

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