user1181690
user1181690

Reputation: 1523

How to clear individual file inputs?

Below is part of the jquery code I have which displays the file input and a "Clear File" button.

var $imagefile = $('<input />')
    .attr({
        type: 'file',
        name: 'imageFile',
        class: 'imageFile'
    });

$image.append($imagefile);

var $imageclear = $('<input />')
    .attr({
        type: 'button',
        name: 'imageClear',
        class: 'imageClear',
        value: 'Clear File'
    });

$(".imageClear").click(function(event){
  event.preventDefault();
  $(".imageFile").replaceWith("<input type='file' class='imageFile' />");
});

Now if you look at the bottom of the jquery code, it shows a function I am using where if the user clicks on the "Clear File" button, it replaces the file input so that if you have chose a file but then want to clear the input, then it does this by replacing the input.

The problem though is that lets say I have two "imageFile" inputs (each file input contains its own "Clear File" button" and they both contain a file, then lets say I want to clear the first file input only, when I click on the "Clear File" button, it clears both file inputs, even though I only want it to clear one file input. So how do I code it so that each "Clear file" button only clears the file input it belongs to?

Upvotes: 0

Views: 155

Answers (1)

Matteo-SoftNet
Matteo-SoftNet

Reputation: 531

Supposing the input and the button are inside the same container (es.div), change that line to:

$(this).parent().find(".imageFile").replaceWith("<input type='file' class='imageFile' />");

Upvotes: 2

Related Questions