Cole Z.
Cole Z.

Reputation: 83

Get text content and write to HTML with JavaScript

I am trying to make a little game thing where you can enter words and such, but the main issue is that when I try to make JavaScript print out the words I write; it doesn't ever work properly! Here is my HTML:

<input id="verb" name="verb" type="text" placeholder="Enter a verb">
<input id="noun" name="noun" type="text" placeholder="Enter a noun">
<button onclick="getWords()">Enter</button>
<p id="output"></p>

And here's the JavaScript to go with it:

var verb = document.getElementById("verb").textContent;
var noun = document.getElementById("noun").textContent;
      function getWords()
      {
          document.getElementById("output").textContent = "You chose " +verb+ " as your verb, and " +noun+ " as your noun";
      }

When you click the enter button in Google Chrome; it simply says that "You chose undefined as your verb, and undefined as your noun."
Why doesn't it recognize the contents of the elements and just fill them with "undefined," no matter what is entered? Is there an easier way to do this? Thanks in advance!

Upvotes: 0

Views: 1704

Answers (2)

Dan
Dan

Reputation: 212

You're very close. In your html, try to use

    function getWords() {

    var verb = document.getElementById("verb").value;
    var noun = document.getElementById("noun").value;

      document.getElementById("output").innerHTML = "You chose " + verb + " as your verb, and " + noun + " as your noun.";
    }

This is the way you need to do it - the way you have written your code, the vars verb and noun are never read. by including them inside the function getWords(), you ensure that the value will only be looked at AFTER the user has clicked the button.

Upvotes: 0

Hunter Larco
Hunter Larco

Reputation: 780

Try

  function getWords()
  {
      var verb = document.getElementById("verb").value;
      var noun = document.getElementById("noun").value;
      document.getElementById("output").innerHTML = "You chose " +verb+ " as your verb, and " +noun+ " as your noun";
  }

value holds the text in an input whereas innerHTML represents the HTML in an element. Therefore you need to read the values of the inputs and store them in the HTML of the paragraph element.

Upvotes: 2

Related Questions