【问题标题】:Form submitting even though it's encased in an if statement, and condition is not met?表单提交,即使它包含在 if 语句中,并且条件不满足?
【发布时间】:2011-10-18 05:57:09
【问题描述】:

我有一个完整的验证码绑定到$('#post-button').click。想法是,变量e_exit 设置为true,然后表单内的数据经过一系列检查。如果它满足任何 if 语句的条件,则会显示一条带有问题的消息,并将e_exit 设置为false。除了问题是,它没有正确完成,因为表单仍在提交(比如显示消息后的四分之一秒)。

我在这里处理的是布尔值,所以类型转换肯定不是问题,我真的不明白发生了什么:

$('#post-button').click( function() {
    var e_exit = true;
    var notif_message = '<div class="notification red"><div class="cross"></div>';

    var name = $('input[name=name]').val();
    var url = $('input[name=url]').val();
    var urlrgx = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/i;
    var urltst = urlrgx.test(url);

    if(name == '' || name == 'Enter a name for this offer') {
        $('#notification').html(notif_message + "You need to enter a name for this offer name. Try to pick something that you'll easily remember when seen again.</div>");
            e_exit = false;
    }

    if(!urltst) {
        $('#notification').html(notif_message + "You need to enter a valid offer url prefixed with http:// for this offer.</div>");
            e_exit = false;
    }

    var rotation_select_val = parseInt($('select[name=r_id]').val());
    if(rotation_select_val != 0) {
        var min_val = isNaN($('input[name=r_min]').val());
        var max_val = isNaN($('input[name=r_max]').val());

        if(min_val || max_val) {
            $('#notification').html(notif_message + "You need to enter a numeric value for your rotation's min and max hits for this offer.</div>");
            e_exit = false;
        }
    }

    var geo_select_val = $('select[name=g_country\\[1\\]]').val();          
    if(geo_select_val != 0) {
        var geo_url_val = $('input[name=g_url\\[1\\]]').val();
        var geo_urltst = urlrgx.test(geo_url_val);

        if(!geo_urltst) {
            $('#notification').html(notif_message + "You need to enter a valid url prefixed with http:// for your geo-location targets.</div>");
            e_exit = false;
        }
    }

    if(e_exit) {
         $('form').submit();   
    }
});

任何关于为什么会发生这种情况的答案,或带有解释的编辑都会有很大帮助!

【问题讨论】:

    标签: javascript jquery if-statement boolean


    【解决方案1】:

    如果#post-button是提交按钮,则需要返回false停止表单提交。

    更好的解决方案是绑定到表单的submit 事件:

    $("#your-form").submit(function() {
        // validate...
    
        return e_exit;
    });
    

    仅当您从事件处理程序返回 true 时,才允许提交表单。

    编辑:

    也许ajax插件也订阅了post按钮的click事件?在这种情况下,我会返回 false 并确保阻止事件进一步传播,如下所示:

    $("#post-button").click(function(ev) {
        // validation
        ev.stopPropagation();
        return false;
    });
    

    【讨论】:

    • 这不是一个提交按钮,问题是它已经绑定到一些 ajaxForm 插件(我现在希望我没有使用过),我根本没有时间重新集成一切和 ajaxForm 插件,我宁愿理解为什么如果 e_exit 设置为 false,它仍然提交。
    猜你喜欢
    • 1970-01-01
    • 2023-02-01
    • 2012-12-17
    • 1970-01-01
    • 2015-07-12
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 2011-02-01
    相关资源
    最近更新 更多