Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 288
Purrell Avatar asked Jan 24 '10 01:01

Purrell


1 Answers

You can suppress submit clicks by doing something like:

$('input[type=submit]').bind('click', function(e) {
    e.preventDefault() // prevents the form from being submitted
    clickHandler(); // the custom submit action
});

Or, you can suppress the actual form submit like this:

$('form').bind('submit', function(e) {
    e.preventDefault();
    // etc
});
like image 139
David Hellsing Avatar answered Oct 29 '22 11:10

David Hellsing