Abhishek
Abhishek

Reputation: 191

Clear a dynamically created div

I have a file input type that is used to select files. On the onchange event of the file selector I am displaying the selected file in a div with an [-] in front of them to detach that file from the div. Below is the code I am using to clear the div of the file with [-] sign:-

$.each(myFileList.files, function (i, val) {
        strFileNames += "<div id=\"" + myFileList.files[i].name.split(' ').join('_').split('.').join('_') + "\">" + myFileList.files[i].name + "<a class=\"removeFileUpload\" style=\"cursor: pointer; text-decoration: none;\" title=\"Remove File from Upload List\" data-filename=\"" + myFileList.files[i].name.split(' ').join('_').split('.').join('_') + "\">[ - ]</a></div>";
});

Now on the click of class "removeFileUpload" i have another function as follows:-

function ehRemoveChosenFile() {
    $("body").on({
        click: function () {
            var fileName = $(this).data("filename");
            alert(fileName);
            var id = "'#" + fileName + "'";
            $(id).empty();
        }
    }, '.removeFileUpload');
}

But this function is not working.

I have also tried:-

$(id).replaceWith('');

Please let me know what I am doing wrong.

Regards Abhishek

Upvotes: 0

Views: 98

Answers (2)

Anjo
Anjo

Reputation: 76

var id = "'#" + fileName + "'";

The ID which you have appended is in single quotes which is not a valid selector. This will consider as $("'#yourId '")

Change this to

var id = "#" + fileName;

then you can use either

$(id).empty();
        or
$(id).html('');

Upvotes: 0

Irvin Dominin
Irvin Dominin

Reputation: 30993

Your id variable is not a valid selector (because of the ' quotes will have a value like "'#demo'"), change it in:

var id = "#" + fileName;

Upvotes: 4

Related Questions