1

I have a button with an id of #file_add_btn. When clicking this button a file input is appended to my form:

<input type="file" class="btn_browse" name="file_uploads[]">

I create an array to store the filenames for checking whether the selected file is already selected previously by any previous file inputs.

When I try to alert the count of array filename_array it is giving me an error in the console:

TypeError: filename_array.count is not a function

var filename_array = [];       
$(document).on('change', '.btn_browse', function() {
    filename_array.push($(this).val().split('\\').pop());
    alert(filename_array.count($(this).val().split('\\').pop()));
});
0

1 Answer 1

2

There is no count() method on an array. There is a length property, but that only gives you the total number of items it holds.

To do what you require you could instead use indexOf() to check if the array already holds the value you want to add, like this:

var filename_array = [];       
$(document).on('change','.btn_browse', function() {
    var selectedFilename = $(this).val().split('\\').pop();
    if (filename_array.indexOf(selectedFilename) != -1) {
        alert('file already selected');
    } else {
        filename_array.push(selectedFilename);
        alert('file added to array');
    }
});

Working example

Alternatively you could just use a single file input with the multiple attribute set so that multiple unique files can be uploaded through a single control, like this:

<input type="file" class="btn_browse" name="file_uploads[]" multiple="multiple" />
Sign up to request clarification or add additional context in comments.

2 Comments

I am not having file with multiple attribute.But I need to use multiple file inputs.When I use this code.its saying file already selected in the first case itself
No problem :) I added a working example to the answer for you anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.