I'm trying to make a simple page that asks you for your name, and then uses name.length (JavaScript) to figure out how long your name is.
This is my code so far:
<script> var name = prompt("What's your name?"); var lengthOfName = name.length </script> <body> </body>
I'm not quite sure what to put within the body tags so that I can use those variables that I stated before. I realize that this is probably a really beginner level question, but I can't seem to find the answer.
Use the <var> tag in HTML to add a variable. The HTML <var> tag is used to format text in a document. It can include a variable in a mathematical expression.
The <var> element in HTML defines a text as a variable and can be used to define variables of a mathematical expression or variables of a piece of code. The text enclosed in the <var> element is normally displayed in italics.
JavaScript Display PossibilitiesWriting into an HTML element, using innerHTML . Writing into the HTML output using document.write() . Writing into an alert box, using window.alert() . Writing into the browser console, using console.log() .
Answer: Use the concatenation operator (+) The simple and safest way to use the concatenation operator ( + ) to assign or store a bock of HTML code in a JavaScript variable. You should use the single-quotes while stingify the HTML code block, it would make easier to preserve the double-quotes in the actual HTML code.
You don't "use" JavaScript variables in HTML. HTML is not a programming language, it's a markup language, it just "describes" what the page should look like.
If you want to display a variable on the screen, this is done with JavaScript.
First, you need somewhere for it to write to:
<body> <p id="output"></p> </body>
Then you need to update your JavaScript code to write to that <p>
tag. Make sure you do so after the page is ready.
<script> window.onload = function(){ var name = prompt("What's your name?"); var lengthOfName = name.length document.getElementById('output').innerHTML = lengthOfName; }; </script>
window.onload = function() { var name = prompt("What's your name?"); var lengthOfName = name.length document.getElementById('output').innerHTML = lengthOfName; };
<p id="output"></p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With