1

我正在創建一個ASP.NET MVC 5應用程序。我需要編寫一些jQuery或JavaScript來檢查表單提交時應用程序的表單是否有效(使用jQuery Validate)。如果表單有效,那麼表單需要同時提交併顯示警告框(現在)。到目前爲止,我已經使用this post來雕刻我的代碼,但它不適合我。此代碼工作正常:當ASP.NET MVC 5應用程序中的表單有效時觸發jQuery函數

$('form').submit(function() { 
    alert('test'); 
}); 

但是,這並不爲我工作:

$('form').submit(function() { 
    if ($(this).valid()) { 
    alert('the form is valid'); 
    } 
}); 

我收到以下錯誤:

Uncaught TypeError: $(...).valid is not a function

我不明白爲什麼這個代碼爲其他人工作,但它不適合我。我哪裏錯了?

如何獲取提交按鈕同時顯示警告框並在表單有效時提交表單?

回答

0

您正在使用哪個版本的jquery? 當我在Chrome瀏覽器的網絡選項卡中選中時,我遇到了同樣的錯誤,我的應用程序使用jQuery 1.10.2。 jQuery驗證程序僅適用於1.7.2,1.8.3,1.9.1,1.11.1,3.1.1。 這是按插件頁面 - https://jqueryvalidation.org/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script> 

<script> 
    $(document).ready(function() { 

    $('#sampleForm').submit(function() { 
     if ($(this).valid()) { 
      alert('valid'); 
     } 
     else { 
      alert('not valid'); 
     } 
    }); 
}); 
</script> 
<div class="jumbotron"> 
    <h1>ASP.NET</h1> 
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p> 
    <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p> 
</div> 

<div class="row"> 
    <form id="sampleForm"> 
    <input type="text" /> 
    <input type="submit" value="Submit" /> 
    </form> 
</div> 

如果你正在使用VS MVC項目,檢查bundleConfig.cs,它的下載不同版本的jQuery。確保它下載所需的jQuery版本或在配置中註釋下載jQuery以進行測試的行。

相關問題