且构网

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

在动态添加多个字段时进行Bootstrap验证

更新时间:2023-12-01 12:41:40

如果在input循环中插入方法addField,它应该可以工作.我还建议将您的第一个row保存为模板.

if you insert the method addField in your input loop, it should work. I also suggest to save your first row as a template.

var template = $('#line_1').clone();
var options = {
    fields: {
        'firstField[]': {
            validators: {
                notEmpty: {
                    message: 'Enter a value 1'
                }
            }
        },
        'secondField[]': {
            validators: {
                notEmpty: {
                    message: 'Enter a value 2'
                }
            }
        },
        'thirdField[]': {
            validators: {
                notEmpty: {
                    message: 'Enter a value 3'
                }
            }
        }
    }
};
$('#myForm').bootstrapValidator(options);

$('#cloneButton').click(function () {
    var rowId = $('.row').length + 1;
    var validator = $('#myForm').data('bootstrapValidator');
    var klon = template.clone();          
    klon.attr('id', 'line_' + rowId)
        .insertAfter($('.row').last())
        .find('input')
        .each(function () {
            $(this).attr('id', $(this).attr('id').replace(/_(\d*)$/, "_"+rowId));
            validator.addField($(this));
        })                   
});