2

Hello I am using the following code to add file inputs to my form:

var addFile = document.getElementById('addFile');
addFile.onclick = function addFile() {
    if (this.count == undefined) {
        this.count = 0;
    }
    if (this.count++ < 2) {
        $(".files").append('<tr><td><input type="file" name="uploaded_file[]" class="file_input" size="46" style="margin-top:1px;"/><a class="delete" href="javascript:void(0)" style="color:blue; padding-left:15px;">Remove File</a></td></tr>');
    }
    if (this.count == 2) {
        alert('If you wish to upload more than 3 files \nplease compile them into a .zip or .rar file');
    }
};

The following code is used to remove a file input.

$(function () {
    $(".delete").live("click", function () {
        $(this).parent().remove();
    });
});

What I am looking for is a way to perhaps combine the two where when I remove a file the overall input count is -1 the same way as it is +1 when added. This way if a user adds a slot then removes one then re-adds one the count is consistent. Any help is welcomed.

Cheers

4

1 に答える 1

2

Instead of storing and persisting a count, get the count each time.

addFile.onclick = function addFile() {
    var count = $(".files tr .file_input").length;
    if ( count < 3 ) {
        // append the row
    }
    else {
        // don't append the row
    }
}

It may be slightly less efficient, but it is more manageable.

于 2012-08-29T20:06:42.100 に答える