0

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?

Nix
  • 57,072
  • 29
  • 149
  • 198
user1181690
  • 1,443
  • 2
  • 11
  • 12
  • possible duplicate of [How to clear File Input](http://stackoverflow.com/questions/9617738/how-to-clear-file-input) – Felix Kling Mar 08 '12 at 13:01
  • You should not create a new question for this. Clarify your original one. What you ask for is how to find a certain node relative to another node. That depends on the actual structure of your DOM. jQuery provides many DOM traversal methods, you just have to find the right one. http://api.jquery.com/category/traversing/ – Felix Kling Mar 08 '12 at 13:01
  • You need a way to identify the correct input from the button, either by traversing the DOM or using another method (such as a unique class, storing the ID of the input as a `data-*` attribute of the button, etc). – Anthony Grist Mar 08 '12 at 13:05
  • Hi, Sorry for this, I will keep that in mind for next time :) – user1181690 Mar 08 '12 at 13:09

1 Answers1

2

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' />");
Matteo-SoftNet
  • 531
  • 3
  • 10