-1

So im trying to stop a form from refreshing the page and this is the code i'm using:

$("#getName").submit(function(refresh) {
    refresh.preventDefault();
    $("#p22").fadeOut(50);
    $("#p23").fadeIn(800);
    document.getElementById("p23").innerHTML = "Oh " + userName + ", alright i wont forget that!";

})

I can't seem to get this working properly....

id = getName - is the form id

Miguel
  • 310
  • 1
  • 5
  • 17

3 Answers3

1

Your question is similar to: https://stackoverflow.com/a/6462306/986160

Try this:

$("#getName").submit(function(refresh) {
    $("#p22").fadeOut(50);
    $("#p23").fadeIn(800);
    $("#p23").html("Oh " + userName + ", alright i wont forget that!");
    return false;
})

By returning false is like refresh.preventDefault() and refresh.stopPropagation() together ;) See details here: https://stackoverflow.com/a/1357151/986160

Community
  • 1
  • 1
Michail Michailidis
  • 11,792
  • 6
  • 63
  • 106
1

I got this sample code of the jQuery documentation and it seems to work fine (it alert's but then doesn't link to destination.html. Everything seems fine in your code, it's probably something different you're looking for.

http://api.jquery.com/submit/

$( "#target" ).submit(function( event ) {
  alert( "Handler for .submit() called." );
  event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="target" action="destination.html">
  <input type="text" value="Hello there">
  <input type="submit" value="Go">
</form>
<div id="other">
  Trigger the handler
</div>
Daan
  • 2,680
  • 20
  • 39
0

Returning false will not validate your form and your page will not be refreshed.

$("#getName").submit(function(refresh) {
    refresh.preventDefault();
    $("#p22").fadeOut(50);
    $("#p23").fadeIn(800);
    document.getElementById("p23").innerHTML = "Oh " + userName + ", alright i wont forget that!";
    return false;
})
Falydoor
  • 462
  • 6
  • 19
  • return false; is like refresh.preventDefault(); and refresh.stopPropagation(); so you don't need the refresh.preventDefault() on the top. Check this: http://stackoverflow.com/a/1357151/986160 – Michail Michailidis Oct 15 '14 at 11:44