How to store prompt value in javascript?

prompt() instructs the browser to display a dialog to the user to input some message. This is an optional message prompting the user.

Prompt is generally used to take the input from the user. When the prompt box pops up, the User has to click “OK” or “Cancel” to proceed.

In this article, we are going to store prompt value in the session.

HTML

<!DOCTYPE html>
<html>
<body>

<h2>The prompt() Method</h2>

<p>Click the button to demonstrate the prompt box.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>



</body>
</html>

Javascript

function myFunction() {
  let prompt_value = prompt("Please enter your name");
  if (prompt_value != null) {
    
    sessionStorage.setItem("key_name", prompt_value);

    let value = sessionStorage.getItem("key_name");

    document.getElementById("demo").innerHTML = value;

  }
}

To store the prompt value, we have used the sessionStorage of javascript here. At the last, we get the store data from the session and show it using innerHTML.

The Element property innerHTML gets or sets the HTML or XML markup contained within the element.

Basic usage of sessionStorage

// Save data to sessionStorage
sessionStorage.setItem('key', 'value');

// Get saved data from sessionStorage
let data = sessionStorage.getItem('key');

// Remove saved data from sessionStorage
sessionStorage.removeItem('key');

// Remove all saved data from sessionStorage
sessionStorage.clear();

I hope the above code will be helpful for you.