I have javascript code which copy the value of input file and past it in the text box in real time.
<script>
function copyit(){
var thephoto=document.getElementById('thephoto').value;
var fileonchange=document.getElementById('fileonchange')开发者_运维技巧.value;
if(!thephoto==fileonchange){
document.getElementById('fileonchange').value=thephoto;
}
}
window.setInterval("copyit()", 500);
</script>
Choose File : <input type="file" id="thephoto"><br>
Here Is the file name : <input type="text" id="fileonchange">
Sadly this only works one time and then stops pasting the value when changing the file again. ( i mean you should reload the page to works again)
Is IF
has a cache or something? you can try the code by yourself to see.
Thank you all
The syntax is wrong. You need the !=
operator to denote inequality:
if (thephoto != fileonchange) {
The !thephoto
actually inverses its boolean representation (i.e. true
becomes false
and vice versa, also null
becomes true
). The ==
actually compares the equality of the both operands.
Try changing the IF line to:
if(thephoto!=fileonchange){
BalusC is completely right, but IMHO using a timer every 500ms to do this simple task seems pretty heavy.
Why don't you simply use the onchange
event of the <input type="file" />
?, e.g.:
window.onload = function () {
var thephoto = document.getElementById('thephoto');
var fileonchange = document.getElementById('fileonchange');
thephoto.onchange = function () {
// this function will be executed when the user changes the file
fileonchange.value = this.value;
};
};
Check the above example here.
The input element, as the W3C says, accepts the onchange
method. Why don't you do:
<input type="file" id="thephoto" onchange="copyit()">
Instead of using the dreaded setInterval?
Use !==
for strict inequality.
Or, if you want to use something similar to the syntax you've written, do this:
if(!(thephoto==fileonchange)){
精彩评论