Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i stop the form from reloading using Javascript?

Tags:

javascript

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?

like image 613
Ibrahim Azhar Armar Avatar asked Mar 01 '11 04:03

Ibrahim Azhar Armar


People also ask

How do you stop a form from reloading?

Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.

How do I stop a form from submitting multiple times?

Use JQuery to Prevent Multiple Form Submissions To prevent the user from submitting a form multiple times, we'll use JQuery to listen for the submission event. Once the form is submitted, we'll add a disabled attribute to the button to prevent multiple form submissions. Now the user can't click it again.

How do I stop HTML from refreshing?

To do not refresh the page we add event. preventDefault(); at the end of our JavaScript function.

How do you prevent a form from clearing fields on submit in JavaScript?

You can use preventDefault method of the event object.


2 Answers

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

like image 61
Shad Avatar answered Sep 19 '22 23:09

Shad


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

like image 33
Matt King Avatar answered Sep 18 '22 23:09

Matt King