how to stay on the same page after clicking submit button

梦想与她 提交于 2019-12-11 04:54:26

问题


I'm creating a login form and in that if any input is wrong then i want to stay on the same page and notify the client to enter the correct input I want to stay on this page http://localhost:8080/loginpage/ but after every click i'm redirected to http://localhost:8080/loginpage/?UserName=UserName&pword=&ConfirmPassword=&Email=Email&FirstName=First+Name&LastName=Last+Name&cars=male&Signup=Signup .

I have written a code for this but it does not seem to work.

if(t!==0)
 {
     var er="Email-id already exists";
     window.location.reload(false); 
     document.getElementById("nemail").value=er;
     document.getElementById("username").value=username;
     document.getElementById("pword").value="";
     document.getElementById("confpwd").value="";
     document.getElementById("fname").value=fname;
     document.getElementById("lname").value=lname;
     document.getElementById("gender").value=gender;
 }

I have tried to use several other methods like

 window.location.replace('/loginpage/');

 window.location.href="/loginpage/index.html";

But none of them works. Please help!


回答1:


There are two ways to prevent a form to submit.

  1. Set form onsubmit="return false".
  2. Register a submit event on a from. In the callback call event.preventDefault();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>1 way to prevent form to submit via onclick attribute</h2>
<form action="#submit-from-1-way" onsubmit="return validate(this)"><!--set onsubmit="return false"-->
    <input name="value"/>
    <button type="submit">Submit</button>
</form>

<h2>2 way to prevent form to submit via submit event</h2>
<form id="form" action="#submit-from-2-way"><!--set onsubmit="return false"-->
    <input name="value"/>
    <button type="submit">Submit</button>
</form>


<script>
    console.log(location.href+'#'+location.hash+'?'+location.search);
    function validate(form) {
        return $(form).find('input').val();
    }
    
    $('#form').submit(function (e) {
        if (!validate(this)) e.preventDefault();
    });
</script>



回答2:


You can use preventDefault() on the click event for a given html object. This will prevent the browser from taking the default action on a specific HTML object.

For example to prevent actoin on a link:

<body>
 <a href="http://www.google.com" id="clickMe">Click Me</a>
<script>

function dontGo(event) {
    event.preventDefault();
}

document.getElementById("clickMe").addEventListener("click",dontGo);

</script>

</body>


来源:https://stackoverflow.com/questions/42542300/how-to-stay-on-the-same-page-after-clicking-submit-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!