Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent submit button with onclick event from submitting

I want to prevent a submit button with onclick event from submitting:

$j('form#userForm .button').click(function(e) {
    if ($j("#zip_field").val() > 1000){
        $j('form#userForm .button').attr('onclick','').unbind('click');
        alert('Sorry we leveren alleen inomstreken hijen!');
        e.preventDefault();
        return false;
    }
});

This is the submit button:

<button class="button vm-button-correct" type="submit"
 onclick="javascript:return myValidator(userForm, 'savecartuser');">Opslaan</button>

It will show the "alert" function and also removes the onclick event, but the form is submitted anyway. Manually remove the onclick event before submitting will solve the problem. However this is core functionality of and I dont want to remove it.

EDIT:

It's definitely caused by the onclick selector.. How can I force my jQuery script to instantly reload the onclick event? adding before jquery code: $j('form#userForm .button').attr('onclick',''); will solve issue.. however my validation won't work an anymore...

like image 225
Coen Ponsen Avatar asked Feb 22 '13 15:02

Coen Ponsen


People also ask

How do you stop re submitting a form after clicking back button?

You can check if the user clicked the back button, disable form if true. Another way is by storing a cookie which you check on page load, if it exists you can disable the form.

How do you stop a form from getting submitted?

The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.

How do I stop form submit when onclick event return false?

Use the return value of the function to stop the execution of a form in JavaScript. False would return if the form fails to submit.


1 Answers

You'll need to add the event as a parameter:

$j('form#userForm .button').click(function(event) { // <- goes here !
    if ( parseInt($j("#zip_field").val(), 10) > 1000){
        event.preventDefault();
        $j('form#userForm .button').attr('onclick','').unbind('click');
        alert('Sorry we leveren alleen inomstreken hijen!');
    }   
});

Also, val() always returns a string, so a good practice would be to convert it to a number before you compare it to a number, and I'm not sure if you're really targeting all .button elements inside #userForm inside the function, or if you should use this instead?

If you're using jQuery 1.7+, you should really consider using on() and off() for this.

like image 155
adeneo Avatar answered Sep 29 '22 01:09

adeneo