zankudo zankudo - 7 months ago 15
Javascript Question

Javascript trigger request with a button?

I am learning JavaScript, I have reached a section called "creating objects", since I am a novice in programming I cant figure out how to trigger the "prompt" request by using a button, instead of being triggered when the page loads, any idea?

myobjt = new Object();
var reqPrompt = prompt("Type a word:");
myobjt.mnfstInput = reqPrompt;
function mFunc() {
document.write(this.mnfstInput);
}
myobjt.mnfstScreen = mFunc;
myobjt.mnfstScreen();

Answer

While both of the other answers are correct, and are a very good way to do it, I'll try to answer using an object

<script>
var myObject = {
     input: "",
     popup: function(){
         alert("Hello, " + this.input);
     },
     setInput: function(){
         this.input = prompt("Enter Name");
     }
 }
 </script>
 <button type="button" onclick="myObject.setInput()">Input</button>
 <button type="button" onclick="myObject.popup()">Output</button>

Edit: https://jsfiddle.net/u1yfsp4z/4/

Comments