【问题标题】:How to prevent a page from reload when an error occurs?发生错误时如何防止页面重新加载?
【发布时间】:2025-12-04 08:40:01
【问题描述】:

我正在编写一个从表单获取用户输入的代码,我编写了一个 javascript 代码来检查表单中的字段是否为空。它运行良好,但有一个问题我一直在尝试解决,但我无法解决。如果有任何空白字段,则错误消息会正确出现,但在重置所有内容后页面会立即重新加载。我在网上搜索了很多,并试图在 javascript 文件中返回 false,甚至将按钮类型更改为“按钮”,但没有任何效果。

这是写在表单中的提交按钮代码,

<input type="submit" value="Update" name="Update" class="submitbutton" >

这是用于验证的 javascript 文件,

var emptyfields=0;// to count the errors
function init()
{
    var myForm = document.getElementById( "myForm" ); //calling forms by ID     
    emptyfields=0;

  myForm.onsubmit = check;// if the admin click submit (check function will be called) 
  myForm.onreset = clear;// if the admin click clear (clear function will be called) 

} // end function init

function check()
      {                                                                     
                if(document.getElementById("name").value=="")//check if the name filed is empty
                {
                    document.getElementById("invalid_name").innerHTML="You must fill the Name field";   
                    document.getElementById("name").style.borderColor="red";//change the color of the border's filed into red
                    emptyfields+=1;//increment it to count the error

                }
                    else
                    {
                        document.getElementById("invalid_name").innerHTML=""; //set the error message to empty
                        document.getElementById("name").style.borderColor="black";//return the original border's filed color
                    }

                if(document.getElementById("quantity").value=="") //check if the quantity field is empty
                {
                    document.getElementById("invalid_quantity").innerHTML=" You must fill this field with a number"; //show the quantity error message
                    document.getElementById("quantity").style.borderColor="red"; //change the boarder color of quantity filed to red
                    emptyfields+=1; //increment the number of errors
                }
                    else
                    {
                        document.getElementById("invalid_quantity").innerHTML=""; //set the quantity error message to "" in order to hide it
                        document.getElementById("quantity").style.borderColor="black"; //reset the border of the quantity field to black 

                    }

                //check if the price field is empty
                if(document.getElementById("Price").value=="") 
                {
                    document.getElementById("invalid_price").innerHTML=" You must fill this field with a number"; //show the price error message
                    document.getElementById("Price").style.borderColor="red"; //change the border color of price field to red
                    emptyfields+=1; //increment the number of errors
                }
                    else
                    {
                        document.getElementById("invalid_price").innerHTML=""; //set the price error message to "" in order to hide it
                        document.getElementById("Price").style.borderColor="black"; //reset the border color of the price field to black
                    }

                if(document.getElementById("image2").value=="") //check if the image field is empty
                {
                    document.getElementById("invalid_image").innerHTML=" You must upload an image"; //show the image error message
                    emptyfields+=1; //increment the number of errors
                }
                    else
                    {
                        document.getElementById("invalid_image").innerHTML=""; //set the image error message to "" in order to hide it
                    }

                if(document.getElementById("Description").value=="") //check if the description field is empty
                {
                    document.getElementById("invalid_Description").innerHTML=" You must fill the Description field"; //show the description error message
                    document.getElementById("Description").style.borderColor="red"; //change the border color of description field to red
                    emptyfields+=1; //increment the number of errors
                }
                    else
                    {
                        document.getElementById("invalid_Description").innerHTML=""; //set the description error message to "" in order to hide it
                        document.getElementById("Description").style.borderColor="black"; //reset the border color of the description field to black
                    }

                if (emptyfields >0) //check if there is any input error made by the user
                {
                    return false; //if yes return false
                }
                    else
                    {
                        return true; //if no return true
                    }       

    }//the end of the check function    

function clear()
      {                                                         
         return confirm( "Are you sure you want to reset?" );  //ask the user if she is sure about resetting the fields.
      }

window.addEventListener( "load", init, false ); //add a load event listener to the window which triggers init function that calls check and clear functions to perform the validation and reset

谁能告诉我如何防止页面重新加载?

非常感谢任何帮助。

谢谢。

【问题讨论】:

    标签: javascript html validation


    【解决方案1】:

    onsubmit 回调使用 event 参数调用,该参数可用于停止触发其默认行为的事件。将您的代码更改为:

    function check(e) {
        // your validation code ...
        if(error) {
            e.preventDefault();
        }
    
    }
    

    您可以了解更多here

    这通常比使用 return false 更可取,原因总结在 this answer

    【讨论】:

    • 非常感谢您的回答,能告诉我e代表什么对象吗?
    • 它表示传递给onsubmit回调的参数。回调将由“父代码”运行,它可以传递一些参数。如果你传递一个不使用它们但它可以的回调并不重要。您不选择回调的参数,它们是由运行它的任何代码段提供给您的。看看这个答案,希望能把它弄清楚:*.com/a/13004118/609907
    • 谢谢您,非常感谢您的帮助。但是,我已经尝试过了,同样的问题仍然存在,如果有其他解决方案,请告诉我
    • 看看这个小提琴......应该没有任何理由它不起作用? jsfiddle.net/sxzcjxtj/4
    • 没关系,我已经使用 HTML 5 required 属性解决了这个问题。非常感谢
    【解决方案2】:

    您需要通过check()return false;。所以当发生错误时,它会阻止onsubmit 提交表单。

    即。

    myForm.onsubmit = check();
    
    // short version of check
    function check() {
      ...
      if(error) {
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          e.returnValue = false;
      }
      return false;
      }
    }
    

    希望这会有所帮助。

    【讨论】:

    • 非常感谢您的回答,但是我已经在这一行中做到了,if (emptyfields >0) //检查用户是否有任何输入错误 { return false; //如果是返回false } else { 返回true; //if no return true } 但是不行,请问有其他解决方法吗?
    • 把它和@Rich 结合起来,因为我意识到你已经附加了一个窗口监听器
    • @Dania:我已经更新了结合 RichieAHB 建议的示例,原因是由于添加了侦听器 // 它执行 init()、trigger()...validate()。希望这会有所帮助
    • 应该 onsubmit = function() 吗?嗯..即。 check() 不同于 check
    • 是的,我试过了,但还是不行,没关系,我已经使用 HTML 5 required 属性来解决问题。非常感谢
    最近更新 更多