Prompt Boxes in Javascript  

The Prompt box allows the user to enter information. A prompt box will appear with text entry field which is similar to a form input type="text" and 2 buttons: OK and Cancel button.

0 526 Technology | Javascript
Wed Dec 26 , 2018

The benefits of using a prompt are fairly limited and the use of forms would often be preferred (from a user perspective). The prompt box title text cannot be changed and the same applies to button text.

If the user clicks the OK button, the value entered into the prompt box will be set. If the user clicks the Cancel button, a null value (empty string) will be set, or a default value if you set it as the second argument in the function. The value returned is either the text entered or null.

A prompt box can be displayed using Javascript's prompt() function.


Syntax

prompt("Text to display in the prompt box, "Default value");

Example



<html>
<head>

<script type="text/javascript">
function fn_prompt() 
{
	var favBrand = prompt("What is your favorite brand?", "");

	//with the value that the user entered
	if (favBrand  != null)
	{
	  alert("Your favorite brand is " + favBrand);	
	}
	
	//no value was entered by user
	else 
	{
	  alert("You did not specify your favorite brand");
	}
}
</script>

</head>
<body>

<form>
<input type="button" onclick="fn_prompt()" value="Click Me" />
</form>

</body>
</html>



Output



Subscribe & Get Regular Updates On Your E-mail