How Do You Assign a Variable in JavaScript from User Input?

Problem scenario
You want to read input and assign it as a variable in JavaScript. What should you do?

Solution
Create a .html file, saved directly on your desktop or in a /var/www/html/ directory on a web server, with the follow content to illustrate how to do this (then open it in a web browser):

<!DOCTYPE html>
<html>
<body>

<h2>Use JavaScript to Change Text</h2>
<p>This example writes "Hello in JavaScript from Continualintegration.com!" into an HTML element with id="demo":</p>

<p id="demo"></p>

<script>

var foo = prompt("Please enter input and press enter");
alert(foo)

</script> 

</body>
</html>

Leave a comment

Your email address will not be published. Required fields are marked *