Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use this JavaScript variable in HTML?

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.

like image 596
Joseph Avatar asked May 04 '15 17:05

Joseph


People also ask

How do you call a variable in HTML?

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.

Can you use variables in HTML?

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.

How do I display JavaScript results in HTML?

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() .

How do you assign a block of HTML code to a JavaScript variable?

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.


1 Answers

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>
like image 170
Rocket Hazmat Avatar answered Sep 19 '22 13:09

Rocket Hazmat