Brett Canfield
Brett Canfield

Reputation: 71

Stop page from reloading on failed validation

I currently have working javascript validation, so that form will not be sumbitted without at least one checkbox being selected. It will throw a message to the user to make sure to select at lease one user.

What I would like to do now, is to stop the form from doing anything else, it appears to reload the page after I click on the submit button, and it would be preferable if it didn't do this.

MY current code is as follows:

Form:

 <form name="frm_multi_message_form" id="multi_message_form" style="margin-bottom: 0px;"  method="post"><button style="border-style: none; margin: 5px 0 5px 0;" type="submit" action="" onClick="checkForm(this);"  >Message multiple sitters</button>
    </form>

My Javascript:

  function checkForm(form)
      {

    if (document.querySelector('form[id="multi_message_form"] input[name="username[]"]:checked')) {
            document.frm_multi_message_form.action = "http://example.com/another-page/";
            document.frm_multi_message_form.submit();
        } else {
            alert("You must select at least one sitter to message");

        }
    return false;
      }

I don't have an issue throwing the alert, and the form submits , I'd like to know how to fire off preventDefault(or is this not allowed in a javascript query??) if I could, so nothing happened other than the error being displayed.

Upvotes: 1

Views: 1875

Answers (3)

Rajesh Dey
Rajesh Dey

Reputation: 173

use "return false" after validation like

$("#formId").submit(function()
{
  if(someField == "")
   {
     $("#divId").text();
      return false;
   }
}

Upvotes: 0

Tim Gupta
Tim Gupta

Reputation: 104

You need an event handler on the form submission to prevent the default behavior (submission):

document.getElementById('multi_message_form').addEventListener('submit', function(evt) {
    evt.preventDefault();
})

Upvotes: 0

Muhammad Usman
Muhammad Usman

Reputation: 10148

You should use onClick="return checkForm(this);" and your form won't be submitted in case of validation error

Upvotes: 2

Related Questions