我为其中一种表格编写了JS验证,我希望用户仅填写几个字段。代码如下。我不希望用户填写所有字段。验证进行得很好,但是单击“提交”按钮时,页面未重定向到目标页面。感谢有人可以帮助我在此处找到差异。提前致谢。
JS代码:
RenderDomConfig : function(e) {
e.preventDefault();
const discount_threshold = e.target.elements.discount_threshold.value;
const discountThreshold = e.target.elements.discountThreshold.value;
const cpThreshold = e.target.elements.cpThreshold.value;
const markdownCpThreshold = e.target.elements.markdownCpThreshold.value;
const minInventoryThreshold = e.target.elements.minInventoryThreshold.value;
const variationMode = e.target.elements.variationMode.value;
if (discount_threshold < 0 || discount_threshold > 100){
alert("Please enter valid discount threshold between 0 to 100");
e.target.elements.discount_threshold.focus();
return false;
}
if (discountThreshold < -16 || discountThreshold > 100){
alert("Please enter valid discount threshold between -16 to 100");
e.target.elements.discountThreshold.focus();
return false;
}
if (cpThreshold < -16 || cpThreshold > 100){
alert("Please enter valid CP threshold between 0 to 100");
e.target.elements.cpThreshold.focus();
return false;
}
if (markdownCpThreshold < 0 || markdownCpThreshold > 100){
alert("Please enter valid markdownCpThreshold threshold between 0 to 100");
e.target.elements.markdownCpThreshold.focus();
return false;
}
if (minInventoryThreshold < 0 || minInventoryThreshold > 100){
alert("Please enter valid minimum Inventory Threshold between 0 to 100")
e.target.elements.minInventoryThreshold.focus();
return false;
}
if (variationMode == "disabled" || variationMode == "enabled" || variationMode == "" ){
return true;
}
else{
alert("Please enter valid variation mode: disabled or enabled");
e.target.elements.variationMode.focus();
return false;
}
return true;
}
}
调用JS代码:
<form action='/setDomConfig?marketplaceID=<%=@marketplace%>&propertyName=<%=@property_name%>&componentName=<%=@component_name%>&simLink=<%=@sim_link%>' onsubmit= "RenderDomConfigHelper.RenderDomConfig(event)" method="post">
答案 0 :(得分:0)
您使用e.preventDefault();
一种方法是将“提交”按钮类型更改为“仅”按钮,然后在完成验证后,可以提交表单。
// click event for the button
document.f.validation.onclick = (e) => {
// validation code...
// when done submit the form.
document.f.submit();
};
<form name="f" action="success.php">
<input type="button" name="validation" value="Submit">
</form>
document.f.submit()
将触发表单的onsubmit事件,因此您仍然拥有该代码将不起作用的效果,如果您将其保留为空或至少不添加e.preventDefault();
,则更好
答案 1 :(得分:0)
您不需要定义e.preventDefault();
。
只需进行以下提交表单事件:
onsubmit = "return RenderDomConfigHelper.RenderDomConfig(event);"