Gautam P Behera
Gautam P Behera

Reputation: 171

How to save the values of an array within an hidden input field before it gets replaced with a new array

I have an application where users can upload images into database through a form. A maximum of 6 photos can be uploaded. User can either select 6 photos simultaneously or can select photos individually max 6 times prior to submitting the form. I then have a hidden input field that gets the file name selected as per below.

<div id="content" >
    <input type="file" name="files[]" id="filer_input2" multiple>
    <input type="hidden" class="mediafile" name="mediafile"/>
</div>

The problem is when user clicks the upload area the hidden input field looses data previously stored. Below is the jquery bit and a screenshot without input being hidden for demo. I would like to know how can I get the file names added to the input field instead of replacing it when user selects a file 2nd or 3rd time....

    <script>
$(document).ready(function(){
            $('#filer_input2').change(function(){

        var files = $(this)[0].files;
        var output = "";
        if(files.length > 0){

       for (var i = 0; i < files.length; i++) {
            output += files[i].name+",";
        }   

        $(".mediafile").val(output);

            } 
        });
});
</script>

enter image description here

Upvotes: 0

Views: 341

Answers (1)

Gautam P Behera
Gautam P Behera

Reputation: 171

For those of you having this problem, below is how I fixed this:

$(document).ready(function(){

        $('#filer_input2').on('change',function(){
            if(!$(".mediafile").val()){
        var files = $(this)[0].files,
            output = "";
        for (var i = 0; i < files.length; i++) {
            output += files[i].name+",";
        }           
        $(".mediafile").val(output);

            }else if($(".mediafile").val()){                    
              var prev_input_file = $(".mediafile").val();
              var new_files = $(this)[0].files,
              new_output = "";
              for (var j = 0; j < new_files.length; j++){
                new_output += new_files[j].name+ ",";
              }
             $(".mediafile").val(new_output + prev_input_file)
           }

        });

});

Upvotes: 0

Related Questions