0

Using jquery and bootstrap-jasny I created a dynamic row insert:

Code here

html:

<table id="internalTbl">
    <tr><td><div class="fileinput fileinput-new" data-provides="fileinput"> <span class="btn btn-default btn-file"><span class="fileinput-new">Select file</span><span class="fileinput-exists">Change</span>
    <input type="file" name="name">
    </span> <span class="fileinput-filename"></span>
 <a href="#" class="close fileinput-exists" data-dismiss="fileinput" style="float: none">&times;</a>
    <input type="text" name="namehidden" />
        </td></tr>
</table>
        <button id="addInternal"> add </button>

javascript:

    // add new row to internal listing table
    $("#addInternal").click(function() {
        $("#internalTbl").each(function () {
            var tds = '<tr>';
            $.each($('tr:last td', this), function () {
                tds += '<td>' + $(this).html() + '</td>';
            });
            tds += '</tr>';

            if ($('tbody', this).length > 0) {
                $('tbody', this).append(tds);
            } else {
                $(this).append(tds);
            }
        });

        // clear the last file input field
        $("#internalTbl tr:last .fileinput").fileinput('clear');
    });

For the subsequence, I am not able to assign the file name to the textbox.

Alvin
  • 8,219
  • 25
  • 96
  • 177
  • what is `fileinput()`. What errors are thrown? ID's must be unique so not sure why you have `$("#internalTbl").each` since there can only be one element that matches that selector – charlietfl Jan 03 '15 at 02:18

1 Answers1

0

You need to delegate the change event for dynamically added fileinput. More on delegate. The below code will attach the change event on future elements with class .fileinput

$(document).on('change.bs.fileinput', '.fileinput', function (e) {
    var filename = $(this).closest('tr').find('.fileinput-filename').text();
    $(this).closest('tr').find('input[type="text"]').val(filename);
});

Also I have used two methods of appending, one on click creates the trs and tds manually and other clones the first tr and appends to the table. You can use any one.

var fileinput = $('#internalTbl tr td:eq(0)').html();
var td = '<td>'+fileinput+'</td>';
var tr ='<tr>'+ td+'</tr>';


$("#addInternal").click(function () {
    $("#internalTbl tbody").append(tr);
    $("#internalTbl tr:last .fileinput").fileinput('clear');
});

$("#addInternal2").click(function () {  
    var cloned_elem = $('#internalTbl tr:first').clone();
    $("#internalTbl tbody").append(cloned_elem);
    $("#internalTbl tr:last .fileinput").fileinput('clear');
});

Demo Fiddle

anpsmn
  • 7,217
  • 2
  • 28
  • 44