Search code examples
javascripthtmlloopsprompt

Alerts, prompts, and a final alert


I can't figure out how to make my code to prompt the user for at least 3 times, click button only once, then prompt, if the user does not input something then alert shows up, again prompt, then alert, again prompt then alert… once 3 times the user fails to type something then a final alert shows up like "No more attempts!" after the final alert is clicked, the DIV background color turns grey, could some someone help me? I know how to turn the DIV background into grey, my issue is with what I suppose should be a loop(prompt, alert,prompt,alert)

var mObjt = {
  userInput: "",

  setInput: function() {
    document.getElementById("div1").innerHTML = mObjt.userInput;
  },

  conRequest: function() {
    if (mObjt.userInput != "") {
      mObjt.setInput();
    } else {
      alert("There is no input!");
      mObjt.popRequest();
    }
  },

  popRequest: function() {
    mObjt.userInput = prompt("Enter a word:");
    mObjt.conRequest();
  }
}
<div id="div1" style="width:200px; height:30px; border:1px solid;"></div>
<button type="button" onClick="mObjt.popRequest()">Add Property</button>


Solution

  • Here is a block of script that should do what you're looking to do.

    var mObjt = {
    userInput: "",
    
    setInput: function(){
        document.getElementById("div1").innerHTML = mObjt.userInput;},
    
    popRequest: function(){ 
    var attempts = 0;
    
    while (attempts < 3 && mObjt.userInput === "") {
        attempts++;
        mObjt.userInput = prompt("Enter a word:");
        if (mObjt.userInput === "")
            alert("You must enter a value");
    }
    if (mObjt.userInput === ""){
        alert("No more attempts");
        //disable work
    } else {
        mObjt.setInput();
    }
    
    }}