I am using jQuery File Upload plugin - I have the auto upload file upload set to false and the behavior I have is that as files are added I build up a table showing the file name and a remove button to allow the user to remove the file before uploading. There is then an upload all files button?
So if a user adds a file called foo.txt a row will be created. However if they add foo.txt again it will create another row. I want to check the existing table for that scenario and alert that to the user and not create the row.
The code for the upload so far is:
$('#uploadFile').fileupload({
replaceFileInput: false,
singleFileUploads: true,
add: function(event, data) {
$.each(data.files, function (index, file) {
var rows = $('#files > tr'); // always getting length 0??
data.url = myUrl;
data.type = 'POST';
data.context = $('<tr>'
+ '<td><strong>Selected File : </strong>' + file.name + '</td>'
+ '<td> </td>'
+ '<td><button type="button" class="removeBtn btn btn-default">'
+ '<span class="glyphicon glyphicon-remove-circle"></span>'
+ 'Remove File</button></td>'
+ '</tr>')
.appendTo('#files')
.data('data', data);
});
});
Note the add function gets called once for each file added which is what I want. However when I try to get the rows in the table I am getting a length of 0 all the time - even when I add a file to the table and then add another file - the second time hitting the add method rows length is still 0 when I was expecting it to be 1?
If I am able to get all the rows before I append then I guess I would have to do a $.each on each row to check the current file name against the filename in the row - if it equals any of them then skip out and not run the append code but instead display an alert?
I think the problem is the
'#files > tr'
selector. It selects all<tr>
elements that are direct children of the#files
element, but they aren't direct children because the browser inserts a<tbody>
element in for you. You could try'#files > tbody > tr'
or just'#files tr'
.Here's a jsfiddle that demonstrates this.
You could add the
<tbody>
yourself and then safely use'#files > tbody > tr'
. Of course, you would have to change the call to.append()
then so the new<tr>
gets appended to the<tbody>
instead of the<table>
.