Search code examples
javascripthtmlinnerhtml

Promt to innerhtml


Im making a bot that is succeding to take orders with alerts and prompts. But now I want to instead show it directly on the page. Does anyone know how I can change the prompts to innerHTML in the code, and still manage to make everything function (and continusly going to the next question)?

This is my code:

// Iteration 2
alert(`Hey! Happy to serve you pizza. On our menu we have ${vegetarian.toLowerCase()}, ${hawaiian.toLowerCase()} and ${pepperoni.toLowerCase()} pizza.`)


// Iteration 3 & 5
let orderName = prompt("Enter the name of the pizza you'd like to order today.").toLowerCase()
console.log(`orderName = ${orderName}`)

let orderQuantity
while(true) {
    if (checkOrderName(orderName)) {
        console.log("Right type of pizza")
        orderQuantity = prompt(`How many ${orderName} pizzas do you want?`)
        break;
    } else {
        console.error("Wrong type of pizza")
        orderName = prompt(`we don't have ${orderName} on the menu. Please choose something from the menu:`)
    }
}
console.log(`Exited while loop. orderQuantity = ${orderQuantity}`)

// Iteration 4
let orderTotal = calculatePrice(orderQuantity, pizzaPrice) 
console.log(`orderTotal = ${orderTotal}`)
// alert("Great I'll get started on your " + orderName + " right away. It will cost " + orderTotal + " kr. It will take " + cookingTime(orderQuantity) + " min.")

document.getElementById("pop-up-replacement").innerHTML = `Great I'll get started on your ${orderName} right away. It will cost ${orderTotal} kr. It will take ${cookingTime(orderQuantity)} min.`

```  

Solution

  • Basically, what you need to do is have an html element in which you can display your message / question. Then add an input element so that users can type in their response.

    Example html

    <h2 id="message"></h2>
    <input id="input" />
    <button id="submit">Submit</button>
    

    Then using JavaScript you can display the message by changing the innerHTML of the message element. Then when the user clicks the submit button, use the value of the input to collect their answer.

    Note: This method is asynchronous, so you will have to use the addEventListener to capture clicks, unlike prompt, which pauses the execution of any JavaScript until the user has exited the prompt.