且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

验证动态添加输入字段

更新时间:2023-12-06 11:10:58

您的输入应该有'name'属性。您需要动态添加规则,一种选择是在表单提交时添加它们。

You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.

以下是我测试过的解决方案: p>

And here is my solution that I've tested and it works:

<script type="text/javascript">
   $(document).ready(function() {
        var numberIncr = 1; // used to increment the name for the inputs

        function addInput() {
            $('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
            numberIncr++;
        }

        $('form.commentForm').on('submit', function(event) {

            // adding rules for inputs with class 'comment'
            $('input.comment').each(function() {
                $(this).rules("add", 
                    {
                        required: true
                    })
            });            

            // prevent default submit action         
            event.preventDefault();

            // test if form is valid 
            if($('form.commentForm').validate().form()) {
                console.log("validates");
            } else {
                console.log("does not validate");
            }
        })

        // set handler for addInput button click
        $("#addInput").on('click', addInput);

        // initialize the validator
        $('form.commentForm').validate();

   });


</script>

和html表单部分:

And the html form part:

<form class="commentForm" method="get" action="">
    <div>

        <p id="inputs">    
            <input class="comment" name="name0" />
        </p>

    <input class="submit" type="submit" value="Submit" />
    <input type="button" value="add" id="addInput" />

    </div>
</form>

祝您好运!请批准答案,如果它适合你!

Good luck! Please approve answer if it suits you!