简体   繁体   English

仅在选择字段时如何允许表单提交

[英]how to allow a form submit only when fields are selected

i have a few select fields that are dynamically created by the end user and the only way to control them is by adding a class of attribute to it so that all the selects that are displayed use this class name. 我有一些由最终用户动态创建的选择字段,控制它们的唯一方法是向其添加一个属性类,以便所显示的所有选择都使用该类名。 What i want is when the user presses buy now the form is only submitted when all select fields have a value as in selected. 我想要的是,当用户按下“立即购买”时,仅当所有选择字段都具有选定值时才提交表单。 if their not selected or one of htem is not selected the form returns false and does accordingly. 如果未选择它们或未选择其中之一,则表单将返回false并相应地执行操作。

problem is in the if statement where i check is this.val is empty and if it is to return false it does not work. 问题是在if语句中,我检查的是this.val为空,如果要返回false,则不起作用。 when i press submit the page gets processed. 当我按提交页面得到处理。 what am i doing wrong? 我究竟做错了什么?

thanks 谢谢

this is my code. 这是我的代码。

$(document).ready(function()  {
        $(".btnbuy").click(function() {

            $(".attribute").each(function() {

                if($(this).val() == '') {
                        $(this).css('border','2px solid red');
                        return false;
                }
                else {
                    return true;
                }

            });


        });


});

Try this 尝试这个

$(document).ready(function() {
    $(".btnbuy").click(function() {
        var r = true;
        $(".attribute").each(function() {
            if ($(this).val() == '') {
                $(this).css('border', '2px solid red');
                r = false;
            }
        });
        return r;
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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