JavaScript Equivalent of cin
JavaScript equivalent of cin. Well from what i know is,there aren’t anything like that in JavaScript.
But we can build a simple text box which allow the User to pass the value into the text box. When the user click on the Submit button .The Input will be process and print out within the HTML paragraph tag.
In this Example i will code both the JavaScript and HTML in a single file , just for easy explanation.But in real time that should be a “No no ” as this is not a good practice to mess things up together.
Let Step into the code our JavaScript Equivalent of cin
Under the Code below. I will create a text box to hold the user input , a Submit button. And JavaScript Of Course to make it work.
-
- As Usual create the Structure of our HTML file the Doc type, Header , Body.
- Create a form tag
- Alright , Let create a Header 2 tag name” Username” and create a paragraph tag to ask the user to input his or her Name
- Create a input Text Box and give it an ID value “getTextValue” we will need this later to get the User input data in our JavaScript
- Create a default text in the text box when no text is being enter placeholder=”My Name”
- Now lets create our button , give it a value= “Submit”; assign an onclick event.This event will trigger the JavaScript when the button is being click.
- Now create the Paragraph tag to output the Name when the Submit Button is being click.
- Give your Paragraph tag an ID name called id=”outputText”
- Now you are all set , let create the JavaScript to run this code. Start it by creating a Script tag with type=”text/javascript”
- Create function inputText(value) which is link to the onclick=”inputText(this.value); at the Button tag
- Get the Value from the User Input Text Box using document.getElementById(“getTextValue”).value and assign the user input into the value variable
- Finally append or output the Value into the paragraph tag by using document.getElementById(“outputText”).innerHTML = “My name is ” + value;
- Well we are done here give your self a pat, we have made it
<!DOCTYPE html> <html> <head> </head> <body> <form> <div> <h2>Username</h2> <P>Enter your Name :</P> <input type="text" id="getTextValue" name="username" placeholder="My Name" > <input type="button" value="Submit" id="" onclick="inputText(this.value);"/> </div> </form> <p id="outputText"> </p> <script type="text/javascript"> function inputText(value) { value =document.getElementById("getTextValue").value document.getElementById("outputText").innerHTML = "My name is " + value; } </script> </body> </html>
The output look as below

Check out how to link external JavaScript document via HTML here
If you have any problem about JavaScript can always check out this community overhere