RGriffiths RGriffiths - 25 days ago 14
HTML Question

Executing script from from submit

When using a

button
this works (loader displays until page is loaded):

<script>
$(document).ready(function(){
$(".loader").hide();
$(".overlay").fadeOut(1000);

$('button').click(function() {
$(".loader").fadeIn("fast");
$(".overlay").fadeIn(100);
});
});
</script>


But if I use
Submit
it does not:

I am trying to the following to work:

<script>
$(document).ready(function(){
$(".loader").hide();
$(".overlay").fadeOut(1000);

$("form").submit(function() {
$(".loader").fadeIn("fast");
$(".overlay").fadeIn(100);
});
});
</script>


I have also tried without joy:

$(input[type="submit"]).click(function() {


I want it to work for all Submits on the page and so do not want to use IDs. Any pointers most welcome.

UPDATE

$("form").submit(function(e) {


did the trick.

Answer

You must prevent the default behavior of your form, otherwise it will submit (and the browser will change to the next page [the action in your form]).

To disable the submit action you need to use event.preventDefault() inside the submit/click function.

If you do need to submit the form - you can add a variable to check if the submittion was already prevented, and according to that to prevent (or submit the form within the submit function):

var submitPrevented = false;
$("form").submit(function(e) {
    if (!submitPrevented) {
        submitPrevented = true;
        e.preventDefault()
    }
    $(".loader").fadeIn("fast");
    $(".overlay").fadeIn(100);
    var that = this;
    setTimeout(function() {
        that.submit();
    }, 1000);
});

Notice that I added the e element as a parameter to the function.

Regarding the last code you wrote - there is a syntax error there. This is the correct syntax:

$('input[type="submit"]').click(function() {
Comments