我有一个表单,其中包含将使用JavaScript生成的元素(复选框),我想检查是否至少其中一个被选中。另外,我有几个输入,我想检查它们中是否至少有一个有值。最初的问题是,我编写的代码显示了错误消息,但立即提交了表单。我不能在这里使用服务器端验证,因为这些项是通过JS创建的。而且我不确定是否可以使用服务器端验证来检查是否至少有一个输入字段具有值。
对于这个问题,我尝试使用e.preventDefault();,如果没有值或复选框未选中,它会阻止表单提交,但如果有值,它仍然不会提交表单
这是我尝试过的代码
$(function () {
$("#SubmitForm-btn").click(function () {
$("#fupForm").submit(function (e) {
e.preventDefault();
var valid = true;
//here I'm checking if any of the input field has value.
$('#dataTable tbody tr td input[type=text]').each(function () {
var text_value = $(this).val();
if (!hasValue(text_value)) {
valid = false;
$("#tableEmpty").html("Please Choose a Service");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
})
//here I'm checking if any of the checkbox is checked.
$('.check').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#Person_errorMSG").html("Please choose a person");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Fromcheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#From_errorMSG").html("Please choose a City");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Tocheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#To_errorMSG").html("Please choose a To city");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
});
});
});发布于 2021-10-29 08:33:21
您应该阻止按钮单击事件,而不是表单提交操作。
请参考以下示例代码:
在视图页面中,我们有一个mainform。
<form id="mainform" asp-action="AddAttribute">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="AttributeId" class="control-label"></label>
<input asp-for="AttributeId" class="form-control" />
<span asp-validation-for="AttributeId" class="text-danger"></span>
</div>
...
<div class="form-group">
Is Submit <input type="checkbox" class="isSubmit" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" id="SubmitForm-btn" />
</div>
</form>在上面页面的末尾,添加以下脚本:
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#SubmitForm-btn").click(function () {
event.preventDefault(); //prevent the default submit action.
//check if the checkbox is checked or not.
var ischecked = $(".isSubmit").last().is(":checked");
if (ischecked) {
//alert("Checked");
//if the cleckbox checked, submit the form.
$("#mainform").submit();
}
else {
//alert("Unchecked");
//show notification message. and the form will not submit.
}
});
});
</script>
}结果如下:

https://stackoverflow.com/questions/69744607
复制相似问题