Techy Techy - 7 months ago 37
jQuery Question

Count of jquery array not working

I have a button with an id of

. 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
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() {


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 {
        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" />