0

Hello how I can limit the number of the generated inputs to 10 in this JavaScript example:

<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {    
    rowNum ++;
    var row = '<div id="itemRows"><label for="file_01">File 01</label><input type="file"  name="file[]" multiple>';
    jQuery('#itemRows').append(row);

}

function removeRow(rnum) {
    jQuery('#rowNum'+rnum).remove();
}
</script>
Vidul
  • 10,128
  • 2
  • 18
  • 20
John Siniger
  • 875
  • 2
  • 16
  • 39

3 Answers3

0

Put in a for loop. There is no iteration in your script.

    function addRow(frm) {    
        rowNum ++;
        for(i; i<10; i++){
            var row = '<div id="itemRows"><label for="file_01">File 01</label><input type="file"  name="file[]" multiple>';
            jQuery('#itemRows').append(row);
        }
    }
Skinner
  • 1,461
  • 4
  • 17
  • 27
0

Add a check for the rowNum when both adding and removing, and prohibit adding whenever you are at 10 and removing whenever you are at 0

<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
    if (rowNum < 10) {   
        rowNum ++;
        var row = '<div id="itemRows"><label for="file_01">File 01</label><input type="file"  name="file[]" multiple>';
        jQuery('#itemRows').append(row);
    }

}

function removeRow(rnum) {
    if (rowNum > 0) {
        jQuery('#rowNum'+rnum).remove();
        rowNum--;
    }
}
</script>
eddyjs
  • 1,270
  • 10
  • 20
0

Bind the counter to the function (functions are first class objects and properties like this make sense). Pollution of the global namespace is not recommended.

function addRow() {
    if (!addRow.counter) {
        addRow.counter = 0;
    }

    addRow.counter++;

    if (addRow.counter > 10) {
        // whatever needed
    }
}
Community
  • 1
  • 1
Vidul
  • 10,128
  • 2
  • 18
  • 20