[javascript] Stop form refreshing page on submit

How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?

The validation is setup working fine, all fields go red but then the page is immediately refreshed. My knowledge of JS is relatively basic.

In particular I think the processForm() function at the bottom is 'bad'.

HTML

<form id="prospects_form" method="post">
    <input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" />
    <input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" />
    <input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" />
    <textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>

    <button id="form_send" tabindex="5" class="btn" type="submit" onclick="return processForm()">Send</button>
    <div id="form_validation">
        <span class="form_captcha_code"></span>
        <input id="form_captcha" class="boxsize" type="text" name="form_captcha" placeholder="Enter code" tabindex="4" value="" />
    </div>
    <div class="clearfix"></div>
</form>

JS

$(document).ready(function() { 

// Add active class to inputs
$("#prospects_form .boxsize").focus(function() { $(this).addClass("hasText"); });
$("#form_validation .boxsize").focus(function() { $(this).parent().addClass("hasText"); });
// Remove active class from inputs (if empty)
$("#prospects_form .boxsize").blur(function() { if ( this.value === "") { $(this).removeClass("hasText"); } });
$("#form_validation .boxsize").blur(function() { if ( this.value === "") { $(this).parent().removeClass("hasText"); } });



///////////////////
// START VALIDATION
$("#prospects_form").ready(function() {

    // DEFINE GLOBAL VARIABLES
    var valName = $('#form_name'),
        valEmail = $("#form_email"),
        valEmailFormat = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
        valMsg = $('#form_message'),
        valCaptcha = $('#form_captcha'),
        valCaptchaCode = $('.form_captcha_code');



    // Generate captcha
    function randomgen() {
        var rannumber = "";
        // Iterate through 1 to 9, 4 times
        for(ranNum=1; ranNum<=4; ranNum++){ rannumber+=Math.floor(Math.random()*10).toString(); }
        // Apply captcha to element
        valCaptchaCode.html(rannumber);
    }
    randomgen();


    // CAPTCHA VALIDATION
    valCaptcha.blur(function() {
        function formCaptcha() {
            if ( valCaptcha.val() == valCaptchaCode.html() ) {
                // Incorrect
                valCaptcha.parent().addClass("invalid");
                return false;
            } else {
                // Correct
                valCaptcha.parent().removeClass("invalid");
                return true;
            }
        }
        formCaptcha();
    });

    // Remove invalid class from captcha if typing
    valCaptcha.keypress(function() {
        valCaptcha.parent().removeClass("invalid");
    });


    // EMAIL VALIDATION (BLUR)
    valEmail.blur(function() {
        function formEmail() {
            if (!valEmailFormat.test(valEmail.val()) && valEmail.val() !== "" ) {
                // Incorrect
                valEmail.addClass("invalid");
            } else {
                // Correct
                valEmail.removeClass("invalid");
            }
        }
        formEmail();
    });

    // Remove invalid class from email if typing
    valEmail.keypress(function() {
        valEmail.removeClass("invalid");
    });


    // VALIDATION ON SUBMIT
    $('#prospects_form').submit(function() {
        console.log('user hit send button');

        // EMAIL VALIDATION (SUBMIT)
        function formEmailSubmit() {
            if (!valEmailFormat.test(valEmail.val())) {
                // Incorrect
                valEmail.addClass("invalid");
            } else {
                // Correct
                valEmail.removeClass("invalid");
            }
        }
        formEmailSubmit();

        // Validate captcha
        function formCaptchaSubmit() {
            if( valCaptcha.val() === valCaptchaCode.html() ) {
                // Captcha is correct
            } else {
                // Captcha is incorrect
                valCaptcha.parent().addClass("invalid");
                randomgen();
            }
        }
        formCaptchaSubmit();


        // If NAME field is empty
        function formNameSubmit() {
            if ( valName.val() === "" ) {
                // Name is empty
                valName.addClass("invalid");
            } else {
                valName.removeClass("invalid");
            }
        }
        formNameSubmit();


        // If MESSAGE field is empty
        function formMessageSubmit() {
            if ( valMsg.val() === "" ) {
                // Name is empty
                valMsg.addClass("invalid");
            } else {
                valMsg.removeClass("invalid");
            }
        }
        formMessageSubmit();


        // Submit form (if all good)
        function processForm() {
            if ( formEmailSubmit() && formCaptchaSubmit() && formNameSubmit() && formMessageSubmit() ) {
                $("#prospects_form").attr("action", "/clients/oubc/row-for-oubc-send.php");
                $("#form_send").attr("type", "submit");
                return true;
            } else if( !formEmailSubmit() ) {
                valEmail.addClass("invalid");
                return false;
            } else if ( !formCaptchaSubmit() ) {
                valCaptcha.parent().addClass("invalid");
                return false;
            } else if ( !formNameSubmit() ) {
                valName.addClass("invalid");
                    return false;
                } else if ( !formMessageSubmit() ) {
                    valMsg.addClass("invalid");
                    return false;
                } else {
                    return false;
                }
            }
        });
    });
    // END VALIDATION
    /////////////////
});

This question is related to javascript jquery html forms

The answer is


 $("#buttonID").click(function (e) {
          e.preventDefault();
         //some logic here
 }

Add this onsubmit="return false" code:

<form name="formname" onsubmit="return false">

That fixed it for me. It will still run the onClick function you specify


In pure Javascript, use: e.preventDefault()

e.preventDefault() is used in jquery but works in javascript.

document.querySelector(".buttonclick").addEventListener("click", 
function(e){

  //some code

  e.preventDefault();
})

Just Put return like this:

_x000D_
_x000D_
function validate()_x000D_
{_x000D_
_x000D_
  var username=document.getElementById('username').value;_x000D_
  _x000D_
   if(username=="")_x000D_
   {_x000D_
  return false; _x000D_
   }_x000D_
   if(username.length<5&&username.length<15)_x000D_
   {_x000D_
    alert("Length should between 5 to 15 characters");_x000D_
    return false;_x000D_
   }_x000D_
   _x000D_
   return true;_x000D_
}
_x000D_
body{_x000D_
 padding: 0px;_x000D_
 margin:0px;_x000D_
}_x000D_
_x000D_
input{_x000D_
 display: block;_x000D_
 margin-bottom:10px;_x000D_
 height:25px;_x000D_
 width:200px;_x000D_
}_x000D_
_x000D_
input[type="submit"]{_x000D_
 margin:auto;_x000D_
}_x000D_
_x000D_
label{_x000D_
 display:block;_x000D_
 margin-bottom:10px;_x000D_
}_x000D_
_x000D_
form{_x000D_
  width:500px;_x000D_
  height:500px;_x000D_
  border:1px solid green;_x000D_
  padding:10px;_x000D_
  margin:auto;_x000D_
  top:0;_x000D_
  bottom:0;_x000D_
  left:0;_x000D_
  right:0;_x000D_
  position:absolute;  _x000D_
}_x000D_
_x000D_
.labels{_x000D_
 width: 35%;_x000D_
 box-sizing:border-box;_x000D_
 display: inline-block;_x000D_
}_x000D_
_x000D_
.inputs{_x000D_
 width: 63%;_x000D_
 box-sizing:border-box;_x000D_
 padding:10px;_x000D_
 display: inline-block;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
 <meta charset="UTF-8">_x000D_
 <title>FORM VALIDATION</title>_x000D_
 <link rel="stylesheet" type="text/css" href="style.css">_x000D_
_x000D_
 <script type="text/javascript" src="script.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
 <form action="#">_x000D_
  <div class="labels">_x000D_
   <label>Name</label>_x000D_
   <label>Email</label>_x000D_
  </div>_x000D_
_x000D_
  <div class="inputs">_x000D_
   <input type="text" name="username" id="username" required>_x000D_
   <input type="text" name="email" id="email" required>_x000D_
  </div>_x000D_
  _x000D_
  <input type="submit" value="submit" onclick="return validate();">_x000D_
 </form>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Return true and false from validate(); function as per requirement


In my opinion, most answers are trying to solve the problem asked on your question, but I don't think that's the best approach for your scenario.

How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?

A .preventDefault() does indeed not refresh the page. But I think that a simple require on the fields you want populated with data, would solve your problem.

<form id="prospects_form" method="post">
    <input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" required/>
    <input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" required/>
    <input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" required/>
    <textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
</form>

Notice the require tag added at the end of each input. The result will be the same: not refreshing the page without any data in the fields.


This problem becomes more complex when you give the user 2 possibilities to submit the form:

  1. by clicking on an ad hoc button
  2. by hitting Enter key

In such a case you will need a function which detects the pressed key in which you will submit the form if Enter key was hit.

And now comes the problem with IE (in any case version 11) Remark: This issue does not exist with Chrome nor with FireFox !

  • When you click the submit button the form is submitted once; fine.
  • When you hit Enter the form is submitted twice ... and your servlet will be executed twice. If you don't have PRG (post redirect get) architecture serverside the result might be unexpected.

Even though the solution looks trivial, it tooks me many hours to solve this problem, so I hope it might be usefull for other folks. This solution has been successfully tested, among others, on IE (v 11.0.9600.18426), FF (v 40.03) & Chrome (v 53.02785.143 m 64 bit)

The source code HTML & js are in the snippet. The principle is described there. Warning:

You can't test it in the snippet because the post action is not defined and hitting Enter key might interfer with stackoverflow.

If you faced this issue, then just copy/paste js code to your environment and adapt it to your context.

_x000D_
_x000D_
/*_x000D_
 * inForm points to the form_x000D_
 */_x000D_
var inForm = document.getElementById('idGetUserFrm');_x000D_
/*_x000D_
 * IE submits the form twice_x000D_
 * To avoid this the boolean isSumbitted is:_x000D_
 *  1) initialized to false when the form is displayed 4 the first time_x000D_
 * Remark: it is not the same event as "body load"_x000D_
 */_x000D_
var isSumbitted = false;_x000D_
_x000D_
function checkEnter(e) {_x000D_
  if (e && e.keyCode == 13) {_x000D_
    inForm.submit();_x000D_
    /*_x000D_
      * 2) set to true after the form submission was invoked_x000D_
      */_x000D_
    isSumbitted = true;_x000D_
  }_x000D_
}_x000D_
function onSubmit () {_x000D_
  if (isSumbitted) {_x000D_
    /*_x000D_
    * 3) reset to false after the form submission executed_x000D_
    */_x000D_
    isSumbitted = false;_x000D_
    return false;_x000D_
  }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<form id="idGetUserFrm" method="post" action="servletOrSomePhp" onsubmit="return onSubmit()">_x000D_
   First name:<br>_x000D_
   <input type="text" name="firstname" value="Mickey">_x000D_
   <input type="submit" value="Submit">_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


<FORM NAME=frm1 ...>
Name: <input type=textbox name=txtName id=txtName>
<BR>
<input type=button value="Submit" onclick=Validate()>



<Script>
    function Validate() { 
        Msg = ""

// Check fields
        if(frm1.txtName.value fails this) {
            Msg += "\n    The Name Field is improper"
        }
// Do the same for the rest of the form

        if(Msg == "") {
            frm1.submit()
        } else {
            alert("Your form has errors\n" + Msg)
        }
    }
</SCRIPT>

The best way to do so with JS is using preventDefault() function. Consider the code below for reference:

function loadForm(){
    var loginForm = document.querySelector('form'); //Selecting the form
    loginForm.addEventListener('submit', login);    //looking for submit
}

function login(e){
    e.preventDefault(); //to stop form action i.e. submit
}

The best solution is onsubmit call any function whatever you want and return false after it.

onsubmit="xxx_xxx(); return false;"

You can use this code for form submission without a page refresh. I have done this in my project.

$(function () {
    $('#myFormName').on('submit',function (e) {

              $.ajax({
                type: 'post',
                url: 'myPageName.php',
                data: $('#myFormName').serialize(),
                success: function () {
                 alert("Email has been sent!");
                }
              });
          e.preventDefault();
        });
});

Sometimes e.preventDefault(); works then developers are happy but sometimes not work then developers are sad then I found solution why sometimes not works

first code sometimes works

$("#prospects_form").submit(function(e) {
    e.preventDefault();
});

second option why not work? This doesn't work because jquery or other javascript library not loading properly you can check it in console that all jquery and javascript files are loaded properly or not.

This solves my problem. I hope this will be helpful for you.


<form onsubmit="myFunction(event)">
    Name : <input type="text"/>
    <input class="submit" type="submit">
  </form>
  <script>
  function myFunction(event){
    event.preventDefault();
    //code here
  }
  </script>

Most people would prevent the form from submitting by calling the event.preventDefault() function.

Another means is to remove the onclick attribute of the button, and get the code in processForm() out into .submit(function() { as return false; causes the form to not submit. Also, make the formBlaSubmit() functions return Boolean based on validity, for use in processForm();

katsh's answer is the same, just easier to digest.

(By the way, I'm new to stackoverflow, give me guidance please. )


function ajax_form(selector, obj)
{

    var form = document.querySelectorAll(selector);

    if(obj)
    {

        var before = obj.before ? obj.before : function(){return true;};

        var $success = obj.success ? obj.success: function(){return true;};

        for (var i = 0; i < form.length; i++)
        {

            var url = form[i].hasAttribute('action') ? form[i].getAttribute('action') : window.location;

            var $form = form[i];

            form[i].submit = function()
            {

                var xhttp = new XMLHttpRequest();

                xhttp.open("POST", url, true);

                var FD = new FormData($form);

                /** prevent submiting twice */
                if($form.disable === true)

                    return this;

                $form.disable = true;

                if(before() === false)

                    return;

                xhttp.addEventListener('load', function()
                {

                    $form.disable = false;

                    return $success(JSON.parse(this.response));

                });

                xhttp.send(FD);

            }
        }
    }

    return form;
}

Didn't check how it works. You can also bind(this) so it will work like jquery ajaxForm

use it like:

ajax_form('form',
{
    before: function()
    {
        alert('submiting form');
        // if return false form shouldn't be submitted
    },
    success:function(data)
    {
        console.log(data)
    }
}
)[0].submit();

it return nodes so you can do something like submit i above example

so far from perfection but it suppose to work, you should add error handling or remove disable condition


If you want to use Pure Javascript then the following snippet will be better than anything else.

Suppose:

HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Form Without Submiting With Pure JS</title>
        <script type="text/javascript">
            window.onload = function(){
                /**
                 * Just Make sure to return false so that your request will not go the server script
                 */
                document.getElementById('simple_form').onsubmit = function(){
                    // After doing your logic that you want to do 

                    return false 
                }
            }
        </script>
    </head>
    <body>

    </body>
</html>
<form id="simple_form" method="post">
    <!-- Your Inputs will go here  -->
    <input type="submit" value="Submit Me!!" />
</form>

Hope so it works for You!!


For pure JavaScript use the click method instead

<div id="loginForm">
    <ul class="sign-in-form">
        <li><input type="text" name="username"/></li>
        <li><input type="password" name="password"/></li>
        <li>
            <input type="submit" onclick="loginForm()" value="click" />
        </li>
    </ul>
</div>

<script>
function loginForm() {
    document.getElementById("loginForm").click();
}
</script>


Just found a very simple yet working solution, by removing <form></form> from the section I wanted to prevent from posting and refreshing.

<select id="youId" name="yourName">
<select> 
<option value="1</option>
<option value="2</option>
<option value="3</option>
</select>
<input id="formStockVal1" type="number"><br><br>
<form> 
<button type="reset" id="stockCancel">Cancel</button>
<button type="reset" id="stockConfirm">Add</button>
</form>

Here only Buttons submit as they should.


Just use "javascript:" in your action attribute of form if you are not using action.


I hope this will be the last answer


_x000D_
_x000D_
$('#the_form').submit(function(e){_x000D_
  e.preventDefault()_x000D_
  alert($(this).serialize())_x000D_
  // var values = $(this).serialize()_x000D_
  // logic...._x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<form id="the_form">_x000D_
   Label-A <input type="text" name='a'required><br>_x000D_
   Label-B <input type="text" name="b" required><br>_x000D_
   Label-C <input type="password" name="c" required><br>_x000D_
   Label-D <input type="number" name="d" required><br>_x000D_
   <input type="submit" value="Save without refresh">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Replace button type to button:

<button type="button">My Cool Button</button>

Personally I like to validate the form on submit and if there are errors, just return false.

$('form').submit(function() {

    var error;

   if ( !$('input').val() ) {
        error = true
    }

    if (error) {
         alert('there are errors')
         return false
    }

});

http://jsfiddle.net/dfyXY/


One great way to prevent reloading the page when submitting using a form is by adding return false with your onsubmit attribute.

<form action="#" onsubmit="yourJsFunction();return false">
    <input type="text"/>
    <input type="submit"/>
</form>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"