views:

112

answers:

5

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

+6  A: 

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.

BalusC
Thank you so much BalusC, You know, girls suck at code XD
Emily
Honey, that's not related to gender :) Just have a good book/tutorial, motivation and mindset. Happy coding.
BalusC
A: 

Use !== for strict inequality.

Or, if you want to use something similar to the syntax you've written, do this:

if(!(thephoto==fileonchange)){

Jakob
+1  A: 

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.

CMS
CMS, Onchange doesn't work good on ie, you should click somewhere in the page to fire the function of pasting the value :(
Emily
+1  A: 

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?

Ben
+2  A: 

Try changing the IF line to:

if(thephoto!=fileonchange){
Catdirt