[英]<input type=“submit” /> doesn't execute javascript code
實際上,使用提交按鈕提交表單時,我希望執行javascript代碼以檢查數據,如果未填充數據,則打開彈出對話框,因此,不要執行與表單綁定的操作。
不幸的是,即使javascript位於頁面頂部,也不會執行javascript代碼。
你有解決方案嗎 ?
謝謝
我的表格:
@using (Html.BeginForm("AddRecipe", "AddRecipe", FormMethod.Post, new { data_ajax = "false"}))
{
//Set of components to submit
//etc
<input type="submit" data-theme="b" id="addRecipeBtn" onclick="checkDatas();" value="Ajouter ma recette" />
}
我要執行的JavaScript代碼:
<script>
function checkDatas() {
alert("ici");
var ok = $("#fakeInput").val().length != 0 &&
$("#title").val().length != 0 &&
$("#cookingTime").val().length != 0 &&
$("#preparationTime").val().length != 0 &&
$("#ingredientListArea").val().length != 0 &&
$("#preparationArea").val().length != 0;
if (!ok) {
$("#popupDialog").popup("open");
}
}
</script>
我們將需要更多信息來確定它是否或為什么根本不執行。
但是為了防止驗證失敗時提交表單,請使用event.preventDefault()。 當然,這將阻止按鈕的默認行為執行……就您而言,這將阻止表單提交。
function checkDatas(event) {
alert("ici");
var ok = $("#fakeInput").val().length != 0 &&
$("#title").val().length != 0 &&
$("#cookingTime").val().length != 0 &&
$("#preparationTime").val().length != 0 &&
$("#ingredientListArea").val().length != 0 &&
$("#preparationArea").val().length != 0;
if (!ok) {
event.preventDefault();
$("#popupDialog").popup("open");
}
}
我認為您會發現您的表單提交將覆蓋您的onclick處理程序,我認為捕獲表單onsubmit事件會更可靠,因為按鈕的類型為“ submit”
<form onsubmit="checkDatas()">
刪除按鈕的onclick事件。
您是否阻止html表單提交的默認提交動作?
我認為您需要這樣的東西:
function checkDatas(e) {
e.preventDefault();
//the rest of your code
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.