如果条件错误,如何防止提交HTML表单? [英] How to prevent an HTML form from being submitted if the conditions went false?
本文介绍了如果条件错误,如何防止提交HTML表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的 @ Html.BeginForm()
,其中包含一些隐藏字段,如下所示:
I have a simple @Html.BeginForm()
with some hidden fields just as below:
@using (Html.BeginForm("AddToCart", "ShoppingCart", new { id = Model.ProductID }))
{
@Html.HiddenFor(m => m.SelectedQuantity, new { @id = "selectedquantity" })
@Html.HiddenFor(m => m.AvailableColors, new { @id = "selectedcolor" })
@Html.HiddenFor(m => m.SelectedSizes, new { @id = "selectedsize"})
@Html.HiddenFor(x => x.ProductID)
@Html.Hidden("returnUrl", Request.Url.PathAndQuery)
<input id="submit" type="submit" class="btn btn-primary" value="Add to cart" />
}
当隐藏字段值为null时,我想阻止表单提交,这可能吗?如果是,怎么办?隐藏的字段值将通过以下脚本进行更新.
I want to prevent form from submitting when the hidden field values are null, is that possible? If yes how? The hidden field values are update by this below script.
<script type="text/javascript">
$(function () {
$("#quantity").on("change", function () {
var quantity = $(this).val();
$("#selectedquantity").val(quantity).val();
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#selectable").selectable({
selected: function (event, ui) {
$(ui.selected).siblings().removeClass("ui-selected");
$("#selectedsize").val($("#selectable>li.ui-selected").html());
}
});
$("#selectable1").selectable({
selected: function (event, ci) {
$(ci.selected).siblings().removeClass("ui-selected");
$("#selectedcolor").val($("#selectable1>li.ui-selected").html());
}
});
});
</script>
推荐答案
您可以在表单中添加"onsubmit";
You can add "onsubmit" in your form;
@using (Html.BeginForm("AddToCart", "ShoppingCart", new { id = Model.ProductID, onsubmit = "validateForm()" }))
然后像下面这样声明函数 validateForm
:
And then declare the function validateForm
like:
function validateForm(event) {
event.preventDefault();
if ($("#selectedquantity").val() === '' || $("#selectedcolor").val() === '' || $("#selectedsize").val() === '') {
return false;
}
return true;
}
通常,只要您的验证函数返回 false
,就不会提交您的表单.
More generally, anytime your validation function return false
, then your form would not be submitted.
这篇关于如果条件错误,如何防止提交HTML表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文