1

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!

aeshna
  • 83
  • 1
  • 2
  • 9

2 Answers2

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>
Akshay Rathnavas
  • 338
  • 4
  • 16
holi-java
  • 29,655
  • 7
  • 72
  • 83
  • but i also have to prompt the client to enter correct input.Then how will i do that.Only in such cases i want to stay on the same page – aeshna Mar 01 '17 at 21:38
  • I'm sorry,I'm late.I have edit my answer.you can try it in your favorite editor. – holi-java Mar 01 '17 at 22:11
0

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>
Canolyb1
  • 672
  • 5
  • 17