0

I have an input="file" that allows me to select multiple files. I'd like to have each of the files, without the extension, show in a new table row in an html table I have created.

I have the following code which allows me to find the filenames of the files selected in the input="file".

<script type="text/javascript">
        $(document).ready(function(){
            $('input[type="file"]').change(function(e){

                var files = $('#fileholder').prop("files")
                var names = $.map(files, function(val) { return val.name; });

               alert(names);
            });
        });
    </script>

Please keep in mind I am a beginner in jQuery but may understand most of the code.

2 Answers 2

1

In vanilla you could write it like this

(JavaScript must be invoked after Elements exist)

var file_input = document.getElementById('file_input'),
    file_table = document.getElementById('file_table');
    
file_input.addEventListener('change', function (e) {
    var i, j, fn;
    // empty table
    while (file_table.rows.length > 0)
        file_table.deleteRow(file_table.rows.length - 1);
    // add new values
    for (i = 0; i < this.files.length; ++i) {
        j = this.files[i].name.lastIndexOf('.');
        if (j > 0)
            fn = this.files[i].name.slice(0, j);
        else
            fn = this.files[i].name;
        file_table.insertRow().insertCell().textContent = fn;
    }
});
<input id="file_input" type="file" multiple/>

<table id="file_table">
    <tbody>
    </tbody>
</table>


Related documentation

Sign up to request clarification or add additional context in comments.

1 Comment

The lastIndexOf > 0 test is to permit files such as .htaccess showing up, where lastIndexOf gives 0. If indexOf finds nothing, the return value is -1
0

JQuery solution looks like that:

$('#fileholder').change(function(e){
    var files = $('#fileholder').prop("files")
    var names = $.map(files, function(val) { return val.name; });
    $.each(names, function(index){
      $('#names').append('<tr><td>'+names[index].split('.').slice(0,-1).join('.')+'</td></tr>');
    });
});

https://jsfiddle.net/0gebxudp/4/

3 Comments

Thanks this works. I've changed it so it splits only at .mp3 . How could I make it split at other extensions such as .m4a and .wav ?
.split('.').shift() this covers all extensions
@Piort Korlaga Yes but the problem is some music files are named such as Example Song Name (ft. Artist). By using your method anything after the ft. is removed.

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.