0

I plan to show alert box if 2 text input doesn't matched. So far I make the alert box onkeyup, but is there another way on to show alert box after page refresh?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Bireon
  • 179
  • 2
  • 4
  • 18
  • Possible duplicate of [How to show an alert after reloading the page in JavaScript?](https://stackoverflow.com/questions/17986198/how-to-show-an-alert-after-reloading-the-page-in-javascript) – Mebin Joe Mar 20 '19 at 08:51
  • 2
    does it depend on data filled before the page refresh? – Mark Baijens Mar 20 '19 at 08:51
  • Hi @Mark Baijens, yes it depends on page before refresh. On second page first input text using echo value from API response adn the second field statisic value for matched checking – Bireon Mar 20 '19 at 08:54

2 Answers2

1

Use localStorage with beforeunload and unload:

window.onbeforeunload = function() {
    var text1 = document.getElementById("text1").value;
    var text2 = document.getElementById("text2").value;
    localStorage.setItem("match", JSON.stringify(text1 == text2));
};
window.onload = function() {
    if (JSON.parse(localStorage.getItem("match"))) {
        alert("Texts match!");
    } else {
        alert("Texts don't match!");
    }
};
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • Hi, thanks for sample, how to alert if value not matched trying something like JSON.stringify(text1 != text2) but the alert not showing up – Bireon Mar 20 '19 at 09:00
  • Yes sorry @Bireon I'll add that. – Jack Bashford Mar 20 '19 at 09:00
  • Hi @Jack Bashford, i tried it but the alert showing on the first load. what i plan to do is, the alert only show after refresh `
    `
    – Bireon Mar 20 '19 at 09:11
  • @Bireon Try to unset the local storage variable after the alert. The reason it shows on the first pageload is probably because you already set the local storage variable before. – Mark Baijens Mar 20 '19 at 09:24
  • Hi @MarkBaijens, tried to put the `localStorage.clear();` and also with `window.localStorage.clear();` but not working, can you please advice how to do in correct way? – Bireon Mar 20 '19 at 10:11
  • `localStorage.removeItem("match");` should do the job. Glad you got it working. – Mark Baijens Mar 20 '19 at 11:03
-1

Yes, you need javascript.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

The simplest way is to just put this at the bottom of your HTML page:

<script type="text/javascript">
      window.onload = function(){ alert("Hi there"));}
</script>

This will show the alert when the browser considers the page fully loaded. hope this helps...