0

I am trying to refresh the page after 3 seconds if two text boxes are not filled with text.

I have it set to a button, it works fine without the conditions.

function refresh() {
  var txt1 = document.getElementById("txtAccountNumber");
  var txt2 = document.getElementById("txtStaffNumber");

  if (txt1.value == "" && txt2.value == "") {
    setTimeout(function() {
      location.reload();
    }, 3000);
  }
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Your code works if called, and the fields are truly empty: `if (txt1.value.trim() === "" && txt2.value.trim() === "") setTimeout(location.reload, 3000);` – mplungjan Aug 30 '19 at 13:25
  • Maybe try `!txt1.value && !txt2.value` instead. My assumption is `.value` returns undefined – Rajesh Aug 30 '19 at 13:26
  • Try opening up the developer tools (shortcut is F12 on most browsers) and see if there are any errors showing up in the console. – Kei Aug 30 '19 at 13:26
  • 2
    Can you clarify what you mean by `I have it set to a button, it works fine without the conditions` ? – Tom O. Aug 30 '19 at 13:44
  • When you call getElementById you should always check the returned value isn't undefined, never assume that just because your calling it in the same page that it will always be valid. Check txt1 and txt2 before use, then check value with typeof value == "string". – SPlatten Aug 30 '19 at 14:19
  • Feel free to delete the question since it is an X/Y problem you managed to solve - but do read about drawbacks to static in the dupe I posted. Next time give us more information since we all we barking up the wrong tree due to us not knowing your code came from ASP – mplungjan Sep 02 '19 at 05:28

3 Answers3

0

You can wrap a condition inside a timeout to do so.

<script>
    function refresh() {
         var txt1 = document.getElementById("txtAccountNumber");
         var txt2 = document.getElementById("txtStaffNumber");    

         setTimeout(function () {
            if (txt1.value == "" && txt2.value == "")
            {
                 location.reload();
            }
         }, 3000);
    }

</script>
Jaydeep
  • 1,686
  • 1
  • 16
  • 29
0

Use this code in your script.

setTimeout(function(){ validation(); }, 3000);
var flag = 0;
function validation(){
  var txt1 = document.getElementById("txtAccountNumber").value;
  var txt2 = document.getElementById("txtStaffNumber").value;
  
  if(flag != 0){
    setTimeout(function(){
      if(txt1 == '' && txt2 == ''){
         location.reload();
      }
      else{
          validation();
      }
    }, 3000);
  }
  else{
   flag = 1;
   if(txt1 == '' && txt2 == ''){
      location.reload();
    }
    else{
      validation();
    }
  }
}
<form>
    <input type="text" id="txtAccountNumber">
    <input type="text" id="txtStaffNumber">
</form>
0

Thanks for the help it turn out i was using ID's in a asp:TextBox which act weird. I had to add ClientIDMode = "Static" so the function could get the ID's. Works now.