简体   繁体   中英

form keeps getting submit event without pressing submit button

I am trying to make a form so when user click button then it will submit but the problem is that it is keep getting on function even if I am not pressing submit button. here is my code

$(function () {
var url, container, form,
    View = {
        init: function () {
            container   = $('.container');
            form        = $('.search#form');
            console.log(form);
            View.loadViews();
            $(document).on('submit', '#form', View.findView());
        },
        findView: function () {
            console.log('helllo');
            return false;
        },
        loadViews: function (view) {
            $(container).load('search.html');
        }
    };
View.init();
});

In code above the line $(document).on('submit', '#form', View.findView()); keeps calling findView() method whereas I want to call it when user click submit button. How can I fix this?

When you bind it using $(document).on('submit', '#form', View.findView()); , you are essentially calling the function and trying to bind the submit event to what the function returns, which is incorrect. Since findView() is returning false , this is equivalent of saying $(document).on('submit', '#form', false);

You need to bind View.findView() like below:

$(document).on('submit', '#form', View.findView); // note, no () at the end

您应该传递函数引用而不是函数返回值。

$(document).on('submit', '#form', View.findView);

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