Ask your own question, for FREE!
Computer Science 8 Online
OpenStudy (a1234):

HTML/Javascript help? Why are the alert, dialog, and confirm boxes popping up the same message when it's meant to be different in the code?

OpenStudy (a1234):

<!DOCTYPE html> <html> <body> <h2>Alert box.</h2> <button onclick="myFunction()"> Box 1 </button> <script> function myFunction(){ alert("Hi!"); } </script> <button onclick="myFunction()"> Box 2 </button> <script> <p id="demo"></p> function myFunction(){ var x; if (confirm("Which button?") == true){ x = "K!"; }else{ x = "Ok."; } document.getElementById("demo").innerHTML = x; } </script> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var person = prompt("Please enter your name", "Harry Potter"); if (person != null) { document.getElementById("demo").innerHTML = "Hello " + person + "! How are you today?"; } } </script> </body> </html>

OpenStudy (woodrow73):

Imagine all the javascript you wrote being on the same page. You have 3 functions with the same name, which doesn't work. Try naming them differently.

OpenStudy (a1234):

How do I do that?

OpenStudy (woodrow73):

Cleaned it up a bit. https://jsfiddle.net/dnpdw8uh/ ``` <!doctype html> <html> <head> </head> <body> <h2> Alert box. </h2> <button onclick="sayHi()"> Box 1 </button> <br /><br /> <button onclick="whichButton()"> Box 2 </button> <p id="box2demo"> </p> <button onclick="wizard()"> Try it </button> <p id="box3demo"> </p> <script> function sayHi() { alert("Hi!"); } function whichButton() { var x; if (confirm("Which button?") == true){ x = "K!"; }else{ x = "Ok."; } document.getElementById("box2demo").innerHTML = x; } function wizard() { var person = prompt("Please enter your name", "Harry Potter"); if (person != null) { document.getElementById("box3demo").innerHTML = "Hello " + person + "! How are you today?"; } } </script> </body> </html> ```

OpenStudy (a1234):

Thanks for your help! I understand much better now.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!