Last Updated : Jul 1, 2023
The promt() is a method of the window object it instructs the web browser to display a dialogue with a text, text input field and two buttons OK and Cancel.
The dialogue prompts the user to enter some text and wait until the user either submits or cancels it.
Here we defined prompt() method with message ‘What Is Your Age?’ it will displayed on webpage when user loads this program on browser then user can submit their number input of age or cancel it.
If they provide answer for our question then it will stored to variable ‘age’.
In html we defined div tag with id ‘res’ using that we appends result of age as ‘Your userAge Years Old!’ message on webpage by innerHTML.
<!DOCTYPE html> <html> <head> <title>TAKE NUMBER INPUT IN JS</title> </head> <body> <div id="res"></div> <script> var age=prompt("What Is Your Age?"); document.getElementById('res').innerHTML="Your "+age+" Years Old!"; </script> </body> </html>
- <!DOCTYPE html> tag which is instruct the web browser about what version of HTML file written in and it’s not have any ending tag.
- The<html> tag is used to indicate the beginning of HTML document.
- As above shown <head> tag is contains information about webpage and external file links are declared here. <title> tag is used for set the webpage title.
- Both <head> and <title> tags having their pair end tag, so we need to close the ending tags respectively. If you’re not closed anyone of ending tag properly that is also affect the webpage result.
- <body> tag is beginning of main coding part because it contain coding of entire website blocks and elements described here.
- Here we defined an div tag with id attribute value ‘res’ using that we can append user input on webpage.
- In script we defined prompt() method with question ‘What Is Your Age?’ then user result collected and stored to variable ‘age’.
- This prompt method will look like alert box but the difference is it had message what we given with empty input field for user can provide their answers.
- Then we needs to append user input on webpage so we used id ‘res’ for append result ‘age’ with string ‘Your (userage) Years Old!’.
- Both </body>,</html> tags closed respectively. </body> tag indicates the end of body, Then </html> tag indicates the end of HTML document.
When we executes our program on browser we can see the one box at top of webpage with question we defined in script then it had empty input field for receive user answer as result then when user clicks ok that box will disappear and result will displayed on webpage like ‘Your 18 Years Old!’ 18- referred like user given input.