2012-04-27 77 views
1

我正在驗證表單,但是如果驗證未通過,它仍會發布表單。我如何防止這種情況?JQuery基本表單發佈

<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> 

回答

2

我會做這樣的:

<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> 
2

您需要停止從點火提交事件,或當它被激發,由該事件返回false,而不是按鈕的停止它點擊事件。你可以改變你的提交按鈕的行爲如何,或者將提交事件綁定到表單本身。

<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>