Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outdated value issue in JavaScript form

Here's the HTML:

<input type="text" placeholder="Answer..." id="ansbox1">
<input type="submit" onclick="submit1();" id="sp1">

Here's my JS:

var txt1 = document.getElementById("ansbox1").value;
    
function submit1() {
  if (txt1.split(" ").join("") === atob("[base64string]").split(" ").join("")) {
    alert("Yaay!");
  }
  else { 
    alert("Nope, its wrong!");
  }
}

When I put (even the decoded matching string) in the input box, it still always shows "Nope, its wrong!".

Any error?

I referred to this, yet I still get the same issue... JS - Check if the input field equals the solution

like image 465
CoderPro1000 Avatar asked Jul 04 '26 05:07

CoderPro1000


2 Answers

Since txt1 is outside the function call, it has stale data. Put it inside the function call, so it can be updated everytime.

function submit1() {
  var txt1 = document.getElementById("ansbox1").value;
  if (txt1.split(" ").join("") === atob("[base64string]").split(" ").join("")) {
    alert("Yaay!");
  }
  else {alert("Nope, its wrong!");}
}
like image 144
boxdox Avatar answered Jul 05 '26 18:07

boxdox


Your txt1 variable is outside the function, which could have a stale/previous value due to scope. This variable should be put inside the function so that it's always updated:

function submit1() {
  var txt1 = document.getElementById("ansbox1").value;

  if (txt1.split(" ").join("") === atob("[base64string]").split(" ").join("")) {
    alert("Yaay!");
  }
  else {
    alert("Nope, its wrong!");
  }
}
like image 21
Audwin Oyong Avatar answered Jul 05 '26 18:07

Audwin Oyong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!