Html OnSubmit 字段中的 Form If 语句

Html Form If statement in OnSubmit Field

我是 html/php/js 的新手,我 运行 在有条件地提交我的表单时遇到了问题。基本上,我试图做的是让 confirm('Do you want to submit this form?') 函数仅在每个字段都输入了值(checkform() 函数)时才显示。如果两者都为真,则表单将提交。任何帮助将不胜感激,谢谢!

<script type="text/javascript">
function checkform()
{
 var myForm=document.frmhot;
 
 if(myForm.status.value==""){
  alert("Please select a timeframe status."); 
  return false;
  myForm.status.focus();
 }
    if (myForm.line.value==""){
  alert("Please select a line.");
  return false;
 }
 if(myForm.reason.value==""){
  alert("Please select a reason code.");
  return false;
 }
 if(myForm.partnum.value==""){
  alert("Please enter a part number.");
  return false;
 }
 if(myForm.badgescan.value==""){
  alert("Please enter a badge number.");
  return false;
 }
 return true;
  
} 
</script>
<form method="post" action="newhotpartgenerate.php" name="frmhot" 
onclick="if(checkform();){
 confirm('Do you want to submit the form?');
}
>
         
<input class="button_text" type="submit"  value="Submit" name="submit" onclick= "checkform();"  />
</form>

你的想法是对的,只需将你的代码提取到它自己的函数中,然后在 onclick 中调用它。

添加此功能:

function checkAndConfirm() {
     if(checkform()) {
        if (confirm('Do you want to submit the form?')) {
            // submit the form
     }
}

然后从onclick属性调用:

<form method="post" action="newhotpartgenerate.php" name="frmhot" onclick="checkAndConfirm()">

完成工作解决方案,在一定程度上对 IE 兼容性进行更正和调整。

<script>
    function checkform(evt)    {        
        var myForm = document.frmhot;
        var condition = true;
        if(myForm.status.value==""){
            alert("Please select a timeframe status."); 
            myForm.status.focus();
            condition = false;
        }
        if (myForm.line.value==""){
            alert("Please select a line.");
            condition = false;
        }
        if(myForm.reason.value==""){
            alert("Please select a reason code.");
            condition = false;
        }
        if(myForm.partnum.value==""){
            alert("Please enter a part number.");
            condition = false;
        }
        if(myForm.badgescan.value==""){
            alert("Please enter a badge number.");
            condition = false;
        }
        if(condition){ condition =  confirm('Do you want to submit the form?'); }

        if(!condition) {
            if(evt.preventDefault) { event.preventDefault(); }    
            else if(evt.returnValue) { evt.returnValue = false; }    
            else { return false; }
        }
    }
</script>
<form method="post" action="newhotpartgenerate.php" name="frmhot" onsubmit="checkform(event)">
    <input type="text" name="status"/>         
    <input type="text" name="line"/>
    <input type="text" name="reason"/>
    <input type="text" name="partnum"/>
    <input type="text" name="badgescan"/>
    <input class="button_text" type="submit" value="Submit"/>
 </form>