return false在我提交的点击中不起作用

kum*_*mar 2 jquery

这是我用于我的Html.BeginForm的代码..

 $('#PbtnSubmit').click(function() {
            $('#PricingEditExceptions input[name=PMchk]').each(function() {
                if ($("#PricingEditExceptions input:checkbox:checked").length > 0) {
                    var checked = $('#PricingEditExceptions input[type=checkbox]:checked');
                    var PMstrIDs = checked.map(function() {
                        return $(this).val();
                    }).get().join(',');
                    $('#1_exceptiontypes').attr('value', exceptiontypes)
                    $('#1_PMstrIDs').attr('value', PMstrIDs);
                } else {
                    alert("Please select atleast one exception");
                    return false;
                }
            });
        });
Run Code Online (Sandbox Code Playgroud)

在其他blcok我的返回false是不是工作后警报消息也去了我的控制器?

谢谢,这是对的吗?

我试过这样的

 $('#PbtnSubmit').click(function() {
                $('#PricingEditExceptions input[name=PMchk]').each(function() {
                    if ($("#PricingEditExceptions input:checkbox:checked").length > 0) {
                        var checked = $('#PricingEditExceptions input[type=checkbox]:checked');
                        var PMstrIDs = checked.map(function() {
                            return $(this).val();
                        }).get().join(',');
                        $('#1_exceptiontypes').attr('value', exceptiontypes)
                        $('#1_PMstrIDs').attr('value', PMstrIDs);
                    } else {
                        alert("Please select atleast one exception");

                    }
                });
return false;
            });
Run Code Online (Sandbox Code Playgroud)

如果我这样做就提交它什么都不做..

谢谢

mqc*_*hen 8

您想阻止表单在特殊条件下提交吗?

如果是这样,您应首先避免使用click,而是使用submit支持键盘操作的事件.更改要提交的事件后,您可以使用event.preventDefault()它来阻止表单提交.

所以你的代码可能看起来像这样(注意:未经测试):

$('<your form selector>').bind('submit', function(event) {
                $('#PricingEditExceptions input[name=PMchk]').each(function() {
                    if ($("#PricingEditExceptions input:checkbox:checked").length > 0) {
                        var checked = $('#PricingEditExceptions input[type=checkbox]:checked');
                        var PMstrIDs = checked.map(function() {
                            return $(this).val();
                        }).get().join(',');
                        $('#1_exceptiontypes').attr('value', exceptiontypes)
                        $('#1_PMstrIDs').attr('value', PMstrIDs);
                    } else {
                        alert("Please select atleast one exception");
                        event.preventDefault(); // Stop the submit here!
                    }
                });
            });
Run Code Online (Sandbox Code Playgroud)

更多信息在这里:.bind()jQuery API(它在页面的相当远的位置,所以在页面内进行搜索.bind("submit").更多信息:.submit().preventDefault()

  • +1使用preventDefault而不是`return false`.我还建议把它放在`alert()`之前,因为它会阻止执行,直到用户按下ok. (2认同)