10

When a User Submits the form i want to stop the default behavior of the form. ie it should not reload. so that i can perform the AJAX request.

here is the code i used.

<script type="text/javascript">
    function validateForm()
    {
        return false;
    }
</script>
<form action="" name="contact" onsubmit="validateForm();">
    <input type="text" name="name" value="Enter Your Name..."/>
    <input type="submit" name="submit"/>
</form>

this does not stop the form from being submitted or reloaded. how do i achieve this?

Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207

5 Answers5

18

It needs to be onsubmit="return validateForm()"

Shad
  • 15,134
  • 2
  • 22
  • 34
6

You can use the onsubmit attribute as suggested, a more unobtrusive way is to use preventDefault() on the event object passed to the function bound to your onsubmit event:

function validateForm(e) {
    if (e.preventDefault) {
       e.preventDefault();
    }
    e.returnValue = false; // for IE
}

This only works if you bind the event listener to the form, instead of having onsubmit inline.

Edit: here's how you could bind an event listener to the form, which when triggered will pass an Event object (note this is the W3C style, this won't work in IE, but will give you an idea):

var form = document.getElementById('myform');
form.addEventListener('submit', validateForm, false);

When the submit event is triggered, it will call the validateForm function, passing the event object. Here's a really good article on Javascript events:

http://www.quirksmode.org/js/introevents.html

Matt King
  • 2,146
  • 15
  • 8
4

You should use a return in the onsubmit hanlder of the form. Try this version:

<script type="text/javascript">
    function validateForm()
    {
        return false;
    }
</script>
<form action="" name="contact" onsubmit="return validateForm();">
    <input type="text" name="name" value="Enter Your Name..."/>
    <input type="submit" name="submit"/>

Chandu
  • 81,493
  • 19
  • 133
  • 134
2

add a return in your event handler:

onsubmit="return validateForm();"

Otherwise the function executed, but doesn't tell the browser to halt processing.

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
0

Using jQuery:

$('form').on('submit', function() {
  // call functions to handle form
  return false;
});

Basically the same as the above solutions, but I prefer to keep my JS out of my HTML, even the "onsubmit" attribute.

Matt Parrilla
  • 3,171
  • 6
  • 35
  • 54