简体   繁体   English

提交前预先验证表格

[英]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). (注意:我不想使用硬编码的CSS,因为我需要使用类似的代码进行显示,并且不显示)。

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. 我致力于@Aprillion将我链接到的内容。 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. 最后,表格的一部分(下拉菜单中的#16)只有在满足某些条件时才需要出现(基本上,如果一个人选择了第一个答案,那么只有他才能选择第16个问题,因此,基本上,如果此人未在下拉菜单中选择包含15个项目(第16个项目)的任何项目,那么他将无法选择#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 . 您可以将验证绑定到change事件,也可以提交

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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