3

I am creating add remove image upload. When I add 1 image's file, it will automate create new input file property without button clicked (only click on input property).

When I click del icon to delete the image's file, the image's preview has been removed but input property belong the image still exist, and the result all image’s file post by submit include the delete’s image.

Could you help me to modify this javascript so when I delete the image, it also delete the input property belong it's image, please?

    var abc = 0;
    $(document).ready(function() {
    $('body').on('change', '#file', function(){
        if (this.files && this.files[0]) {
            abc += 1;   
            $(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");

            var reader = new FileReader();
            reader.onload = imageIsLoaded;
            reader.readAsDataURL(this.files[0]);

    //      $(this).hide();
            $("#abcd"+ abc).append($("<img/>", {id: 'x', src: 'x.png', alt: 'delete'}).click(function() {
                $(this).parent().remove();
            }));
        }
        $(this).after($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
                    $("<input/>", {name: 'file[]', type: 'file', id: 'file'})
        ));
    });

    //To preview image     
        function imageIsLoaded(e) {
            $('#previewimg' + abc).attr('src', e.target.result);
        };
    });
    #file{
        color:green;
        padding:5px; border:1px dashed #123456;
        background-color: #f9ffe5;
    }

    #x{ 
        width: 17px;
        height: 17px;
        border: none; 
        margin-left: -20px;
        margin-top: 1px;
        cursor: pointer;
        position: absolute;
    }

    .abcd img{
        height:100px;
        width:100px;
        padding: 5px;
        border: 1px solid rgb(232, 222, 189);
    }
    <form enctype="multipart/form-data" action="" method="post">
        <div id="filediv">
            <input name="file[]" type="file" id="file"/>
        </div><br/> 
        <input type="submit" value="Upload File" name="submit"/>
    </form>

running on jsfiddle

1
  • hi, i have fully rewrited your code and made a working demo so that you can go further..! hope it help Commented Oct 2, 2015 at 8:37

4 Answers 4

1

Its too much to rewrite but i can point you to two problems with your code:

  1. hierachy: you keep creating divs inside the previous file-upload divs. These "should" be siblings and not children. Attach things to the .parent() element

  2. ID:s should be unique. You file upload elements and the filedivs all have the same ID, try to add the abc incrementing variable you have to those newly created elements

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

Comments

1

your code completely rewrited and fully working

   var files = [];
    $(document).on('change', '#file', function() {

        var index = $('.file-wrapper').length ? $('.file-wrapper:last-child').data('index') + 1 : 0;

        if (this.files) {

            console.log('files', this.files);

            $.each(this.files, function(i, file) {

                var reader = new FileReader();

                files[index] = file;

                var template = '<div id="file-wrapper-%d" data-index="%d" class="col-4 file-wrapper">' +
                    '<div class="card p-2">' +
                    '<div class="card-header p-2"><strong>' +
                    file.name +
                    '</strong></div><div class="card-body p-2 text-center">' +
                    '<img src="%s" class="img-fluid" alt="" style="max-height:150px" /></div>' +
                    '<div class="card-footer p-2">' +
                    '<a href="#" data-index="%d" class="float-left delete-image btn btn-sm btn-danger"><i class="fas fa-trash-alt"></i></a>' +
                    '<strong class="float-right">' +
                    formatSizeUnits(file.size) +
                    '</strong>' +
                    '</div>' +
                    '</div></div>';


                reader.onload = function(e) {

                    console.log('reader', reader, e);

                    // create the form data object
                    // and pass some additional parameters

                    var data = new FormData();
                    data.append('fileName', file.name);
                    data.append('fileIndex', index);
                    data.append('fileBlob', reader.result);
                    data.append('action', 'upload');

                    // upload to server
                    $.ajax({
                        type: 'POST',
                        url: 'api.php',
                        data: data,
                        processData: false,
                        contentType: false
                    }).done(function(json) {
                        console.log('ajax:upload', json);
                        $('#files-wrapper').append(template.replace(/(%d)/g, index).replace(/(%s)/g, reader.result));
                        $("#file-wrapper-" + index).fadeIn(200);
                        index++;
                    });
                }
                reader.readAsDataURL(file);
            });
        }
    });
  • see the demo source for css code...

4 Comments

unable to view your demo link. Please update your demo link.
@sanoj lawrence: tnx for pointing out the issue, i have updated the code... let me know. ;-)
And can i use <input name="file[]" type="file" id="file" multiple/> how do i use multiple any solution
@sanoj lawrence: i have updated my code, check the demo source and monitor the console log...
0

Try with this below code, I have changed all id attribute to class attribute because you can't make same id for different elements. Id is always unique.

var abc = 0;
$(document).ready(function() {
$('body').on('change', '.file', function(){
	
	if (this.files && this.files[0]) {
		abc += 1;	
		$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
	   
		var reader = new FileReader();
		reader.onload = imageIsLoaded;
		reader.readAsDataURL(this.files[0]);
//		$(this).hide();
		$("#abcd"+ abc).append($("<img/>", {class: 'delete-icon', src: 'x.png', alt: 'delete'}).click(function() {
			$(this).closest(".filediv").remove();
		}));
	}
   	$(this).closest(".filediv").after($("<div/>", {class: 'filediv'}).fadeIn('slow').append(
                $("<input/>", {name: 'file[]', type: 'file', class: 'file'})
   	));
});

//To preview image     
    function imageIsLoaded(e) {
        $('#previewimg' + abc).attr('src', e.target.result);
    };
});
.file{
    color:green;
    padding:5px; border:1px dashed #123456;
    background-color: #f9ffe5;
}

.delete-icon{ 
    width: 17px;
    height: 17px;
    border: none; 
    margin-left: -20px;
    margin-top: 1px;
	cursor: pointer;
    position: absolute;
}

.abcd img{
    height:100px;
    width:100px;
    padding: 5px;
    border: 1px solid rgb(232, 222, 189);
}
<form enctype="multipart/form-data" action="" method="post">
    <div class="filediv">
        <input name="file[]" type="file" class="file"/>
    </div><br/>	
    <input type="submit" value="Upload File" name="submit"/>
</form>

1 Comment

If you compare my html/css/js code with yours then you will get to know the differences that i made :-)
0
<input type="file" id="fileInput" name="image[]" multiple class="opacity-0" />
<div id="thumb-output" class="grid grid-cols-3 gap-2"></div>

<div class="bg-black text-white rounded p-2 cursor-pointer mt-5" id="showFiles">Show Files</div>


<script type="text/javascript">
//Preview
$("#fileInput").on("change", function(e) {
    var files = e.target.files;
    var filesLength = files.length;
    for (var i = 0; i < filesLength; i++) {
        var f = files[i]
        var fileReader = new FileReader();
        fileReader.onload = (function(e) {
            var file = e.target;
            var img = '<div class="img-wrap"><span id="deleteImage" class="delete-image text-2xl cursor-pointer" data-name="'+file.name+'">&times;</span><img class="rounded" src="'+e.target.result+'" ></div>';
            $('#thumb-output').append(img);
        });
        fileReader.readAsDataURL(f);
    }
});

//Remove
$(document).on('click','#deleteImage',function(){
    var pips = $('.img-wrap').toArray();
    var $selectedPip = $(this).parent('.img-wrap');
    var index = pips.indexOf($selectedPip[0]);

    var dt = new DataTransfer();
    var files = $("#fileInput")[0].files;

    for (var fileIdx = 0; fileIdx < files.length; fileIdx++) {
        if (fileIdx !== index) {
            dt.items.add(files[fileIdx]);
        }
    }

    $("#fileInput")[0].files = dt.files;

    $selectedPip.remove();
});

//Check current files
$(document).on('click','#showFiles',function(event){
    event.preventDefault();
    var data = $('#fileInput')[0].files; //this file data
    const fileListArr = Array.from(data);
    var fileName = $(this).data("name");

    for(i = 0; i < fileListArr.length; ++ i){
        console.log(fileListArr[i]);
    }
});

</script>

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.