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);
  }
}
6
  • Your code works if called, and the fields are truly empty: if (txt1.value.trim() === "" && txt2.value.trim() === "") setTimeout(location.reload, 3000); Commented Aug 30, 2019 at 13:25
  • Maybe try !txt1.value && !txt2.value instead. My assumption is .value returns undefined Commented Aug 30, 2019 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. Commented Aug 30, 2019 at 13:26
  • 2
    Can you clarify what you mean by I have it set to a button, it works fine without the conditions ? Commented Aug 30, 2019 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". Commented Aug 30, 2019 at 14:19

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

But how does introduction of if stops calling setTimeout?
Why is that better than not executing the timeout at all?
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>

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.