Skip to content
Advertisement

Check Does an element change?

I wanted to execute a command by changing the value of input c1. I wrote the codes as follows and I do not know why c1 is known as undefined!!

Friends, can you help me how to solve this problem?

var c1=parseInt(document.querySelector("#c1").value.replace(/,/g,""));

setInterval(() => {
    let c2=parseInt(document.querySelector("#c1").value.replace(/,/g,""));
    console.log(c1); // why c1 is undefined?
   
    if(c1!=c2){
     var c1=parseInt(document.querySelector("#c1").value.replace(/,/g,""));
     console.log("change");
    }
},3000)
<input id="c1" value="12000">

Advertisement

Answer

This is because you are re-declaring the same variable (c1) again inside setInterval().

Demo:

var c1 = parseInt(document.querySelector("#c1").value.replace(/,/g,""));

setInterval(() => {
    let c2 = parseInt(document.querySelector("#c1").value.replace(/,/g,""));
    console.log(c1); // why c1 is undefined?
   
    if(c1 != c2){
     c1 = parseInt(document.querySelector("#c1").value.replace(/,/g,""));
     console.log("change");
    }
},3000);
<input id="c1" value="12000">
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement