Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Prompt in Javascript
2.1.
Syntax of javascript prompt
2.1.1.
Optional two parameters of prompt function:
2.1.2.
Example of how to use both parameters with the javascript prompt function
3.
prompt return value 
4.
JavaScript Window.prompt() Method working
4.1.
Example of how to use Window.prompt() Method
5.
Examples to understand Javascript prompt
5.1.
Example 1
5.2.
Example 2
6.
Exceptions of javascript prompt
7.
Frequently Asked Questions
7.1.
How to check the user’s input in the prompt box?
7.2.
How to convert a prompt method string to a number?
7.3.
How to ask for multiple inputs using the prompt method?
7.4.
What are all Web Browsers supported for the prompt method?
7.5.
How to prompt a button in JavaScript?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Javascript Prompt

Author Dhruv Rawat
1 upvote

Introduction

Hello, Ninja. Do you observe something while browsing a website; yes, a pop-up which asks for input that is a javascript prompt. A javascript prompt function allows the developer to collect data from the user directly, making the web more engaging and interactive.

Understanding how to use javascript prompts is an essential skill for every developer. So get ready to enter into the world of javascript prompts!

javascript prompt

Prompt in Javascript

A prompt is a function in Javascript that displays a message box to the user and has only two options “OK” or “Cancel”.The dialogue box would wait for the user to enter any input and loads the webpage afterwards. If the user does not wish to respond to the pop-up/dialogue box, press the Cancel option to cancel it. Generally, it takes a string as input.

Syntax of javascript prompt

The syntax for the javascript prompt function is as follows:-

prompt(message, default)

Optional two parameters of prompt function:

  • message: shows the message that we want to display for the user to enter information and it is an optional parameter. If the input is not provided, the prompt box will display some browser default message.
     
  • default: It is a string value that appears in the input field of the prompt box, and if not provided, the input field will be left blank. It is also an optional parameter and used as an aid for the users.

Example of how to use both parameters with the javascript prompt function

var favLan = prompt("Hey Ninja Coders! Tell us your favourite Coding language?", "Enter name here ");


Output:

output of prompt

In the above example, the prompt box would display a message and the input field, which prompts the user to enter a name.

**Note: The above code is running in the Chrome Browser Console. 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

prompt return value 

The prompt function in javascript returns a string value according to the user's input. If the user enters some value and clicks the ok button, the prompt function will return that value which the user enters otherwise on clicking cancel button, a null value is returned.

JavaScript Window.prompt() Method working

The window.prompt() method is the same prompt() method discussed above, the prompt() is a short-hand name of this. They both are built-in javascript methods and the Window.prompt method also displays a dialog box to the user with an input field and a message. The user entered text is returned or null in case the user clicks the cancel button.

Example of how to use Window.prompt() Method

Let's see how window.prompt() method works by using an example

var favLan = window.prompt("Hey Ninja Coders! Tell us your favourite Coding language?", "Enter name here 👇");
if (favLan !== null) {
  alert("Namaste " + favLan + "coder");
} else {
  alert("Wrong Button");
}


Output:

output of javascript prompt
output of javascript prompt.

In the above example, the prompt box would display a message and the input field, which prompts the user to enter a name and then displays the user entered text if it is a not null value otherwise shows an alert message saying “Wrong Button”.

Examples to understand Javascript prompt

In this section, we are going to implement the javascript prompt method.

Example 1

In this example, we create a prompt box which asks for the user name and displays a message prompt according to the user input value. We are handling non-value entered and cancel button response from the user.

<html>
  <head>
    <title>javascript prompt</title>
    <script>
      var name = prompt("Hey there! Welcome to Coding Ninjas. What's your name?", "Enter your name here");

      // checking for the edge cases when user did not enter a value or click cancel
      if (name === null ) {
        // display error and ask again
        alert("Cannot proceed further without entering your name");      
         }

         // Display a welcome message with the entered name 
        alert("Welcome to Coding Ninjas, " + name );  

    </script>
  </head>
  <body>
  </body>
</html>


Output:

  • Before Click
output  before click
  •  After entering name and Click OK 
output after entering name

Example 2

In this example, we will do the same things we did in the previous example, but here we have added styles to the prompt box and displayed the name in the webpage.

<html>
<head>
<style>
button {
	background-color: #45A29E;
	color: blue;
    cursor: pointer;
}
</style>

<script>
	function showPrompt() {
	var defaultval= "Enter your name ";
	let input = prompt("Please enter your name:", defaultval) ;


	if (input !== null ) {
	document.getElementById("cn").innerHTML = `Welcome to Coding Ninjas, ${input}!`;
	} else {
	document.getElementById("cn").innerHTML = "Error";
	}
}
</script>

</head>
<body style="text-align: center; background-color:#635147;">
<h1 style="color: orange;">Coding Ninjas</h1>
<h2 style="color: #45A29E;">This is Javascript prompt() Method</h2>
  <button onclick="showPrompt()">
Click me!
</button>
<p id="cn"></p>
</body>
</html>


Output:

  • Before Click:
output before click
  • During and After Click:
output during click
output after click

Exceptions of javascript prompt

The exceptions of the javascript prompt are:-

  • null should be properly handled in the case when the user clicks on the cancel button
     
  • "Blocked a frame with origin" error may occur in some browsers if our prompt method is called on a web page that is not active currently. It is a security feature of the web browsers and to fix it refresh the page.
     
  • Entering a lengthy message or default value could lead to bad UI or some browsers would cut the text.
     
  • When the input provided by the user is not a string but an integer then we have to perform casting otherwise it could lead to some error.

Frequently Asked Questions

How to check the user’s input in the prompt box?

To check for invalid or empty input, we could use conditional statements or regular expressions before accepting the value and also can implement the isNaN() method to check whether the return value is a number or not.

How to convert a prompt method string to a number?

By using parseInt or parseFloat functions in javascript, we can change the string to a number and for checking whether we have received a number or not we can use the isNaN() method.parseInt will convert the string to an integer while parseFloat will convert to a floating-point number.

How to ask for multiple inputs using the prompt method?

To ask for multiple inputs from the user we can define multiple prompt function calls and then works on each function call return value according to our need. We can also use a loop to iterate over each input and call the prompt function inside the loop.

What are all Web Browsers supported for the prompt method?

The most modern web browser supports the prompt method, a few names are Google Chrome (version >= 4), Firefox (version >= 2), and Edge (version >= 12).Point to note that some browsers may block the prompt method if it is not called in response to user interaction such as key press or button click.

How to prompt a button in JavaScript?

To prompt a button in JavaScript, use the prompt() method. This method takes two arguments: the first argument is the label that displays in the text box, and the second argument is the default string, which displays in the textbox and it contains two buttons, OK and Cancel. 

Conclusion

Congratulations on finishing this blog!! This article has discussed the javascript prompt and the syntax of the javascript prompt function. We have also discussed examples of how to implement the javascript prompt function.

Hope you enjoyed reading this article, here are some more related articles:

Check out The Interview Guide for Product Based Companies and some famous Interview Problems from Top Companies, like AmazonAdobeGoogle, etc., on Coding Ninjas Studio.

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test SeriesInterview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.

We hope you found this blog helpful in expanding your knowledge. Please give this article a thumbs up if you enjoyed it. 

"Have fun coding!"

Live masterclass