3. Getting Input


Using a Prompt Box

          There are some web pages that would require you to input a value first before entering their page. They are using prompt boxes for that. When this popup box appears, the user needs to click either “OK” or “Cancel” in order to proceed. Once, the user clicks “OK”, it returns the value which the user had entered. On the other hand, if it is cancelled, it returns null. The prompt() method can be used with or without the window keyword.

Sample Code:


          In the sample code above, notice that there are two parameters of the prompt() method. The first one is for the text to be displayed while the second one is the default value of the text box. The values taken from the prompt() method are stored as strings. Thus, in order to convert strings to an integer value, we use the method parseInt(). Without the parseInt() method, the result of the sum would be the concatenation of x and y instead of the sum of x and y.

Note: Other JS functions that convert strings to numeric data type are parseFloat() and Number(). Try to experiment with these two functions to see their differences.