event.prevent验证单选按钮时默认不起作用

event.preventDefault not working when validating radio buttons

本文关键字:默认 不起作用 单选按钮 prevent 验证 event      更新时间:2023-09-26

我正在尝试验证是否选中了所有项目(单选按钮)。以下代码有效,但是一旦我单击警报窗口,它就会再次弹出。使用event.stopPropagation()不会改变任何东西。它不会等待用户检查剩余项目。

$(document).ready(function(){
        $(document).on('submit','#formular',function(event){
            $("input:radio").each(function() {
                var val = $('input:radio[name=' + this.name + ']:checked').val();
                if (val === undefined) {
                    alert("Not every item answered");
                    event.preventDefault();
                    }
                });
            });
        });

你不会使用 preventDefault 退出循环,通常你会使用 breakcontinue ,但在 jQuery $.each 你必须使用 return true 才能继续,return false等效于 break

    $(document).ready(function(){
        $(document).on('submit','#formular',function(event){
            $("input:radio").each(function() {
                var val = $('input:radio[name=' + this.name + ']:checked').val();
                if (val === undefined) {
                    alert("Not every item answered");
                    return false;
                }
            });
            // When invalid formular:
            return false;
            // When it's valid:
            return true;
        });
    });

另请参阅此问题:jquery 验证:阻止表单提交

看:

如何打破 jQuery 每个循环

如何在 JQuery 中断开/退出 each() 函数?

https://api.jquery.com/each/