Last Updated : Jan 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 Name?’ it will displayed on webpage when user loads this program then user can submit their name or cancel it.
If they provide answer for our question then it will stored to variable ‘name’.
In html we defined div tag with id ‘res’ using that we appends result of name as ‘Hi username’ message on webpage by innerHTML.
<!DOCTYPE html> <html> <head> <title>TAKE INPUT IN JS</title> </head> <body> <div id="res"></div> <script> var name=prompt("What Is Your Name?"); document.getElementById('res').innerHTML="Hi "+name; </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 Name?’ then user result collected and stored to variable ‘name’.
- 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.
- We needs to append user input on webpage so used id ‘res’ for append result ‘name’ with string ‘Hi’.
- 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 ‘Hi John’ john- referred as user given input.