/

HTML / CSS / JavaScript Tutorial

JavaScript Window method: prompt()

[this page | pdf | back links]

The prompt() method (when applied to Window objects in the JavaScript BOM) displays text in a dialog box prompting user for input (and with an OK and Cancel button).

 

It has the following syntax with the following parameters. It returns a string if the user clicks OK, being the input value (an empty string if the user didn’t input anything), or null if the user clicks cancel.

 

window.prompt(text, defaulttext)

 

Parameter

Required / Optional

Description

text

Required

String specifying text to display in dialog box

defaulttext

Optional

String specifying default input text

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head></head>
<body>
<button onclick="myOnclick()">Open a prompt box</button><br>
<span id="x1"></span>

<script>
function myOnclick() {
  var x = prompt("Please enter your favourite fruit","apple");
  document.getElementById("x1").innerHTML = "You entered: " + x
}
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodWindowPrompt() {
  return !!window.prompt;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)


Desktop view | Switch to Mobile