动态表单字段中的限制

时间:2016-05-19 10:28:26

标签: javascript

我正在使用一个表单,其中表单字段是在点击时动态添加的。不幸的是,我无法限制添加表单字段。任何帮助将不胜感激。

$(document).ready(function(){ 
    $(".addmore").on('click', function () {
        var count = $('table tr').length;
        var data = "<tr class='case'><td><span id='snum" + count + "'> Field"+ count + ".</span></td>";
        data += "<td><input class='form-control' type='text' id='c1' name='field"+count+"'/></td> </tr>";


        $('#form_table').append(data);
        i++;

    });
    $(".delete").on('click', function () {
        $('tr.case:last').remove();
    });

    //insert into database

    //insert into database
    $('.insert').on('click', function(){
        $.ajax({
            url: 'upload_file.php',
            method: 'post',
            data: $('form#students').serialize(),
            success: function(data){
                $('#record_list').html(data);
            }
        });
    });


});

2 个答案:

答案 0 :(得分:2)

$(document).ready(function(){    
$(".addmore").on('click', function () {
    var count = $('table tr').length;
    if(count >= 5) return;
    var data = "<tr class='case'><td><span id='snum" + count + "'> Field"+ count + ".</span></td>";
    data += "<td><input class='form-control' type='text' id='c1' name='field"+count+"'/></td> </tr>";
    $('#form_table').append(data);

});

答案 1 :(得分:1)

$(document).ready(function() {
    var init = $('table tr').length;
    $(".addmore").on('click', function() {
        var count = init + parseInt($('table tr').length);
       if(count >= 5) { alert('No more rows allowed'); return; }
            var data = "<tr class='case'><td><span id='snum" + count + "'> Field" + count + ".</span></td>";
            data += "<td><input class='form-control' type='text' id='c1' name='field" + count + "'/></td> </tr>";


            $('#form_table').append(data);
            i++;

    });
    $(".delete").on('click', function() {
        $('tr.case:last').remove();
    });

    //insert into database

    //insert into database
    $('.insert').on('click', function() {
        $.ajax({
            url: 'upload_file.php',
            method: 'post',
            data: $('form#students').serialize(),
            success: function(data) {
                $('#record_list').html(data);
            }
        });
    });
});