JavaScript Home

Javascript Example 2: Adding a word to your page

Enter a word into the edit field and use the submit button. Once you submit, your word will be added to the page!



Waiting for your input...

HTML:

<html>
  <head>
    <title>Example 2</title>
    <script src="script.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body> 
    <h1>Example 2: Adding words to your page</h1>
    <label for="words"> Type anything here </label>   
    <input type="text" id="words"  name="words">
    <button type="button" onclick="addWords()">Submit</button>
    <p aria-live="assertive" id="update"> Waiting for your input...</p>
  </body>
</html>

Javascript:

function addWords(){
    var userText = document.getElementById("words").value; //comment: .value returns the string entered into the input
    document.getElementById("update").innerHTML = "You just wrote "+ userText + " in the input!"; //you can combine strings (in quotes) and variables (no quotes) with plus signs
}
    

Next steps: You can use span elements to update specific parts of a paragraph. For example:

  <p>My mother has <span id="updateColor">blue</span> eyes.</p>
  

Once you have a handle on example 2, can you create more text inputs that are used to update span elements in a paragraph in order to create a mad lib?

HTML Element Glossary

Next: Debugging