简体   繁体   中英

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.

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() {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM