在单击“提交”按钮时将表单值添加到数据库的ejs代码将重定向到admin / add。
<form name="addProduct" action="admin/add" method="post" onsubmit="return IsFormValid()">
<div class="row">
<div id="msg-error">
<div class="alert with-close alert-danger">
<span class="badge badge-pill badge-danger">Error!!</span>
<span id="error-text"></span>
</div>
</div>
<div class="col-12 mb-3">
<label for="form-name">Product Name <span>*</span></label>
<input type="text" class="form-control" id="form-name" name="name" value="">
</div>
<button type="submit" class="btn btn-primary btn-services rounded-btn">Add Product</button>
</div>
</form>
脚本是
<script>
document.getElementById("msg-error").style.display = "none";
function IsFormValid(){
document.getElementById("msg-error").style.display = "none";
var ProductName=document.getElementById("form-name").value;
var RegName = /^[A-Za-z ]+$/;
if( ProducName == ""){
document.getElementById("msg-error").style.display = "block";
document.getElementById("error-text").innerHTML="Enter Product Name";
return false;
}else{
alert ("Form Submitted Successfully!");
return true;
}
}
</script>
不起作用,只是将其重定向到表单操作
答案 0 :(得分:1)
表格:在表格中添加ID
<form id="addProductForm" name="addProduct" action="admin/add" method="post">
<div class="row">
<div id="msg-error">
<div class="alert with-close alert-danger">
<span class="badge badge-pill badge-danger">Error!!</span>
<span id="error-text"></span>
</div>
</div>
<div class="col-12 mb-3">
<label for="form-name">Product Name <span>*</span></label>
<input type="text" class="form-control" id="form-name" name="name" value="">
</div>
<button type="submit" class="btn btn-primary btn-services rounded-btn">Add Product</button>
</div>
</form>
脚本:将事件侦听器添加到脚本
<script>
document.getElementById("msg-error").style.display = "none";
document.querySelector("#addProductForm").addEventListener('submit',(event)=>{
document.getElementById("msg-error").style.display = "none";
var ProductName=document.getElementById("form-name").value;
var RegName = /^[A-Za-z ]+$/;
if( ProducName == ""){
document.getElementById("msg-error").style.display = "block";
document.getElementById("error-text").innerHTML="Enter Product Name";
//return false;
event.preventDefault();
}else{
alert ("Form Submitted Successfully!");
//return true;
}
}
</script>
使用event.preventDefault()停止表单的基本执行
有关更多详细信息,请检查我在项目ref code中所做的验证