简体   繁体   中英

JQuery basic form post

I am validating a form but when the validation is not passed it still posts the form. How do I prevent the this?

<form action="/Account/Registration" method="get">
           <fieldset id="enterCode">
                <ul>
                    <li class="inputBlock">
                        <input type="text" id="Code" name="Code" value="">

                    </li>
                </ul>

            </fieldset>
            <div class="submitBlock">
                <input type="submit" value="Send" class="button" onclick="validate();" />
            </div>
        </form>

        <script type="text/javascript">
            function validate() {

                var val = $('#Code').val();

                if (val == "") {
                    alert("Please enter code");
                }

                return false;


                }

        </script>

I'd do it like this:

    <form action="/Account/Registration" method="get" id="registrationForm">
       <fieldset id="enterCode">
            <ul>
                <li class="inputBlock">
                    <input type="text" id="Code" name="Code" value="">

                </li>
            </ul>

        </fieldset>
        <div class="submitBlock">
            <input type="submit" value="Send" class="button" id="submitButton" />
        </div>
    </form>

    <script type="text/javascript">
        $(function(){
          $('#submitButton').click(function(e){ 
             e.preventDefault();
             var val = $('#Code').val();
             if (val.length > 0) {
                 $('#registrationForm').submit();
              }

          });
        });
    </script>

You need to stop the submit event from firing, or when it is fired, halt it by returning false on that event rather than the button's click event. You could change how your submit button behaves like in bunting's example, or bind a submit event to the form itself.

<form action="/Account/Registration" method="get" id="registrationForm">
   <fieldset id="enterCode">
        <ul>
            <li class="inputBlock">
                <input type="text" id="Code" name="Code" value="">

            </li>
        </ul>

    </fieldset>
    <div class="submitBlock">
        <input type="submit" value="Send" class="button" />
    </div>
</form>

<script type="text/javascript">
    $(document).ready(function () {
        $('#registrationForm').submit(function () {
            var val = $('#Code').val();
            if (val == "") {
                alert("Please enter code");
                return false;
            }
            return true;
        });
    });
</script>

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