提交表单后如何在ready事件中传递函数

时间:2018-06-26 14:13:18

标签: jquery forms function submit

我正在尝试根据输入是否有效来确定如何提交表单。因为我有很多条件,所以我想将它们作为函数,但是事情并没有像我使用它那样起作用。

不起作用(工作): https://jsfiddle.net/ba6xjm8d/3/

$(function() {

    $("#Submit").click(function() {
      // validate and process form here

      var name = $("#Name").val();
        if (name == "") {
        return false;
      }

      var surname = $("#Surname").val();
        if (surname == "") {
        return false;
      }   
    });
});

具有功能(不起作用) https://jsfiddle.net/9tq23b7g/1/

function isEmpty(elemInput){
      var elem = $(elemInput).val();
        if (elem == "") {
        return false;
      }
}

$(function() {

    $("#Submit").click(function() {
      // validate and process form here

      isEmpty("#Name");
      /*var name = $("#Name").val();
        if (name == "") {
        return false;
      }*/

      var surname = $("#Surname").val();
        if (surname == "") {
        return false;
      }   
    });
});

有人可以请我解释一下如何正确编写这段不起作用的代码(以便我知道如何使用函数),并请给我一些解释为什么它不起作用。

谢谢!

编辑

基本上,如果我逐个在控制台中启动它,则一切正常,但是当我在ready中调用它时,无论是否返回假参数,都将发送click事件形式。好像根本无法识别。

这是完整的代码片段:

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Form</title>

    <!-- CSS links -->
        <!-- Bootstrap -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">


    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
    <!-- 1. Start Main Header -->
    <header class="main-header" id="mainHeader">
        <div class="container">
            <div class="row">
                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                    <h1>Form</h1>
                </div>
            </div>
        </div>
    </header>
    <!-- / 1. End Main Header -->
    <!-- 2. Start Main Content -->
    <main class="main-content">
        <div class="container">
            <div class="row">
                <div class="register-form col-lg-12 col-md-12 col-sm-12 col-xs-12">
                    <form method="post" action="https://www.google.com/" id="inputForm">

                        <!-- Name -->
                        <div class="form-group" id="nameFormGroup">  
                            <label for="Name" class="control-label">Name</label>
                            <input type="text" name="name" class="form-control" id="Name" placeholder="Name" autofocus/>
                        </div>

                        <!-- Surname -->
                        <div class="form-group" id="surnameFormGroup">   
                            <label for="Surname" class="control-label">Surname</label>
                            <input type="text" name="surname" class="form-control" id="Surname" placeholder="Surname"/ >
                        </div>

                        <!-- Submit Button -->
                        <div class="form-group"> 
                            <button type="submit" id="Submit" class="btn btn-primary">Send</button>
                        </div>    
                    </form>
                </div>
            </div>
        </div>
    </main>
    <!-- / 2. End Main Content -->

    <!-- jQuery -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!-- JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <!-- JavaScript Validation JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
    <script>

    /*  */
    function printError(elemInput, elemFormGroup, msgErr){ 
        $(elemFormGroup).removeClass("has-success has-feedback");
        $(elemFormGroup).addClass("has-error has-feedback");
        $(elemInput).after('<span class="glyphicon glyphicon-remove form-control-feedback"></span>');
        $(elemInput).after('<span class="text-danger">' + msgErr +'</span>');
    }

    /*  */
    function printSuccess(elemInput, elemFormGroup){ 
        $(elemFormGroup).removeClass("has-error has-feedback");
        $(elemInput).after('<span class="glyphicon glyphicon-ok form-control-feedback"></span>');
        $(elemFormGroup).addClass("has-success has-feedback");
    }

    /* This function is working if I try it in console, but not in this piece of code*/
    function checkIsEmpty(elemInput, elemFormGroup){
            var something = $.trim($(elemInput).val());
            if (something == ""){
                printError($(elemInput), $(elemFormGroup), 'Input form is empty');
                alert("I have returned false");
                return false;
            } else {
                printError($(elemInput), $(elemFormGroup));             
            }           
    }

    $(document).ready(function() {
        $("#inputForm").submit(function() {

            var name = $.trim($("#Name").val());
            var surname = $.trim($("#Surname").val());

            $('.text-danger').remove();
            $('.glyphicon').remove();       

            /*name*/
            /*calling function*/
            checkIsEmpty("#Name", "#nameFormGroup");

            /* Tring to replace this piece of code as function that would be called outside ready-submit event */

            /*name*/                    
            /*
            if (name == ""){
                printError($("#Name"), $("#nameFormGroup"), 'Input form is empty');
                return false;
            } else {
                printError($("#Name"), $("#nameFormGroup"));                
            }
            */

            /*surname*/             
            if (surname == ""){
                printError($("#Surname"), $("#surnameFormGroup"), 'Input form is empty');
                return false;
            } else {
                printError($("#Surname"), $("#surnameFormGroup"));              
            }

            // return false;
        });
    });
    </script>
</body>

或者您在此处查看:https://jsfiddle.net/cz6x8on2/

1 个答案:

答案 0 :(得分:1)

您的问题是您在isEmpty函数的返回中没有做任何事情。

function isEmpty(elemInput){
      var elem = $(elemInput).val();
        if (elem == "") {
        return false;
      }
}

$(function() {

    $("#Submit").click(function() {
      // validate and process form here

      isEmpty("#Name"); // not catching result of the call

      // omitted.
    });
});

如果要防止在jQuery中提交表单,则处理函数必须返回false。这不是这里的情况。您可以通过将返回类型存储为变量并返回它来解决它。

$(function() {

    $("#Submit").click(function() {
      // validate and process form here

      const val = isEmpty("#Name"); // not catching result of the call
      // if name is empty then val is false  -> no submit
      if(!val) return false; // stops form submit
    });
});

PS:函数行为与名称矛盾。我希望在未填写输入元素时它返回true。但是您返回false。令人困惑。请重命名该函数,或者如果输入为空,则返回true

编辑:花了一些时间来更新您的小提琴:https://jsfiddle.net/cz6x8on2/8/