Supress submit event / Submit button enabled only if javascript is disabled

By : Purrell
Source: Stackoverflow.com
Question!

I have some client-side JavaScript validation on a form. It works great. But I want to accommodate users who have JavaScript disabled. My validation isn't run from the form's onsubmit attribute, it's an event handler that is bound to a normal button in the form. So the button that kicks off the validation and submit isn't actually a submit, it's just type="button":

<input type="button" value="Ok" class="okbtn">

Then I register an event handler to its click event that does my validation. It submits if everything passes:

function clickHandler(event){
    thisForm = event.data.caller
    var valid = submitValidation(thisForm);
    if (valid == true){
        thisForm.submit();
    } else{
      }
}

My problem is if the user has JS disabled, there is no way to submit the form. I could make the button type="submit", which would work for the JS-disabled users, but then it will *always submit the form and bypass the validation for the JS-enabled users. (The validation will run but it will submit anyway). If I make the button type="submit" can I block the submit event if it's clicked? I'm using JQuery, can JQuery suppress the submit? I want my validation to handle whether it gets submitted.

By : Purrell


Answers

You can suppress the submit by setting the onsubmit handler in the form element, and then if it fails validation return false.

So you would return true if the validation succeeded, or false if it failed, instead of calling thisForm.submit().

By : clee


Change the button to a normal submit button and bind the validation check to the submit() event on the form.

$("form").submit(function() {
  if (!submitValidation()) {
    return false;
  }
});

From the docs:

The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to elements. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form element has focus.

By : cletus


This video can help you solving your question :)
By: admin