0

below script is working fine . but issue is its showing file name in alert box . but i want file name as input value .. I tried many times but i didn't get expected outfile . Example If i selected first file i want input value in id="0" like that if it is 2nd one I want value in id="2"

<input type="file" class="input"/>
<input type="file" class="input"/>
<input type="file" class="input"/>
<input type="file" class="input"/>
<input type="file" class="input"/>
<input id="0">
<input id="1">
<input id="2">
<input id="3">
<input id="4">
<script>
var inputArray = document.getElementsByClassName('input');

for(var i = 0; i < inputArray.length; i++){
    inputArray[i].addEventListener('change',prepareUpload,false);
};

function prepareUpload(event)
{
    var files = event.target.files;
    var fileName = files[0].name;
    document.getElementById("0").value = fileName;
    alert(fileName);
}
</script>
wvs wvs
  • 11
  • 2
  • Try to use something else for IDs instead of the numbers. Seems to work fine for me though: https://jsfiddle.net/1zbtnfzr/ – putvande Feb 11 '16 at 16:45
  • input value is displaying in only one input .. but i want values in different inputs if I uploaded first file I want value in first input . if it is 2nd file i want value in 2nd input – wvs wvs Feb 11 '16 at 16:50
  • Ah ok .. so it works but you just need a bit more code. – putvande Feb 11 '16 at 17:02

1 Answers1

-1

Your IDs are not valid. See this question:

What are valid values for the id attribute in HTML?

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Here is a little demo of what I think you tried to do:

<input type="file" class="input" name="input1" />
<input type="file" class="input" name="input2" />
<input id="input1">
<input id="input2">

var inputArray = document.getElementsByClassName('input');

for(var i = 0; i < inputArray.length; i++){
  inputArray[i].addEventListener('change',prepareUpload,false);
};

function prepareUpload(event)
{
  var files = event.target.files;
  var fileName = files[0].name;
  document.getElementById(event.target.getAttribute('name')).value = fileName;
  alert(fileName);
}

Depending on the use case you might want to use a data attribute instead of the name.

Community
  • 1
  • 1
Ferenc Kamras
  • 174
  • 1
  • 5