Skip to content
Advertisement

Why JavaScript IF only works once?

I have JavaScript code which copies the value of input file and paste 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 once and then stops pasting the value when changing the file again. (I mean you should reload the page to make it work again)

Does IF have a cache or something? You can try the code by yourself to see.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement