Reputation: 15
I need your help. This works so far that I will get alerts when I add a filefield and add files to them. But when I want to change a previous field it will show the last ones value. I have tried using the different id:s but I'm stuck.
Also how to show the filename only in showSrc() here?
upload.html
<form id="uploadForm" action="{% url fileman.views.upload %}" method="post" enctype="multipart/form-data">{% csrf_token %}
<p><input type="file" name="ufile1" id="myfile1" onChange="javascript:showSrc();" size="20"><a href="#" id="myframe1"></a></p>
<p id="addFileFild"><a href="#" id="myframe" onclick="return addFileFild();"><img src="{{ fileman_media_url }}/plus_icon.png"WIDTH=25 HEIGHT=25></a></p>
script.js
function addFileFild(){
ufile = ufile+1;
myfile = myfile+1;
myframe = myframe+1;
$("#addFileFild").before('<p><input type="file" name="ufile'+ufile+'" id="myfile' +myfile+'" onChange="javascript:showSrc();" size="20"><a href="#" id="myframe' +myframe+'"></a></p>');
return 0;
}
function showSrc() {
document.getElementById("myframe"+myframe).href = document.getElementById("myfile" +myfile).value;
var theexa=document.getElementById("myframe"+myframe).href.replace("file:///","");
alert(document.getElementById("myframe"+myframe).href.replace("file:///",""));
}
This is where I would have to get the correct field value each time:
document.getElementById("myfile" +myfile).value;
Here is the solution by Dr.Molle with added C:/fakepath removal for chrome and IE8+.
function showSrc(obj) {
//obj.nextSibling.href = obj.value;
// this is for Chrome and IE8+ excluding C:/fakepath/...
var filename = obj.value.replace(/^.*\\/, '')
//Write filename to page.
obj.parentNode.replaceChild(document.createElement('span'),obj.parentNode.lastChild);
obj.parentNode.lastChild.appendChild(document.createTextNode(filename));
}
Upvotes: 1
Views: 1319
Reputation: 117334
Provide the input as argument to showSrc()
onChange="showSrc(this)"
Inside showSrc access this argument:
function showSrc(obj) {
obj.nextSibling.href = obj.value;
//output the src inside the link
obj.nextSibling.innerHTML = '';
obj.nextSibling.appendChild(document.createTextNode(obj.value));
//......
}
Edited function regarding to the comments:
function showSrc(obj) {
obj.parentNode.replaceChild(document.createElement('span'),obj.parentNode.lastChild);
obj.parentNode.lastChild.appendChild(document.createTextNode(obj.value));
}
Upvotes: 2