0

When I researched on Google, I always see that they need or use a button for the Javascript to work. But what I need is a confirm popup box without using a BUTTON. like when you run the code, the program will appear instantly.

what I need is a confirm popup box without using a BUTTON. like when you run the code, the program will appear instantly.

(I saw in my classmate's work, he used var ().)

<h1>Demo: confirm() </h1>
<button onclick="save()">Save Data</button>
<p id="msg"></p>

<script>
    function save(){     
      var userPreference;

        if (confirm("Do you want to save changes?") == true) {
            userPreference = "Data saved successfully!";
        } else {
            userPreference = "Save Canceled!";
        }

        document.getElementById("msg").innerHTML = userPreference; 
}
Anonymous
  • 835
  • 1
  • 5
  • 21
maxi
  • 1

1 Answers1

0

You can use the load event to show popup box "instantly" when the code runs.

Just add window.onload = save() in your script.

Your updated code becomes:

window.onload = save()

function save() {
  var userPreference;

  if (confirm("Do you want to save changes?") == true) {
    userPreference = "Data saved successfully!";
  } else {
    userPreference = "Save Canceled!";
  }

  document.getElementById("msg").innerHTML = userPreference;
}
<h1>Demo: confirm() </h1>
<button onclick="save()">Save Data</button>
<p id="msg"></p>

Credit to question asker & some answerers: How do I call a JavaScript function on page load?
Part(s)/Whole of this answer have been taken/inspired from them.

Anonymous
  • 835
  • 1
  • 5
  • 21