JS-151-API
  • JavaScript Library
  • 02-DOM-Manipulation
    • Overview
    • DOM Explained
    • Example Setup
    • Selecting Elements
    • Events
    • Complete Example
  • 03-API Fundamentals
    • 0-Getting Started
      • Welcome
    • 1-Intro-To-APIs
      • Intro
      • Client
      • Requests
      • JSON
      • API Endpoints
      • Server
      • Response
      • Statelessness
      • REST
    • 2-Asynchronous-Programming
      • Intro
      • Callbacks
      • Promises
      • Promises Continued
      • Chaining Promises
    • 3-Fetch
      • Fetch Intro
      • Star Wars
        • Star Wars API
        • Star Wars Setup
        • Star Wars JS
      • Random Photo
        • Unsplash
        • Unsplash Setup
        • Unsplash JS
    • 4-Apps
      • 01-New York Times
        • 00-App Intro
        • 01-HTML/CSS/API Key
        • 02-Variables
        • 03-Event Listeners
        • 04-fetchResults
          • 01-fetchResults()
          • 02-preventDefault()
          • 03-fetch() method
          • 04-Dates
        • 05-displayResults
          • 01-Logging JSON
          • 02-Working with JSON
          • 03-Link Display
          • 04-Results Navigation
          • 05-Results Update
          • 06-Keywords
          • 07-Images
        • 06-Pagination
          • 01-Pagination Intro
          • 02-Pagination Functions
        • 07-Next Steps
      • 02-YouTube
        • html
        • youtube.css
        • youtube.js
      • 03-GoogleMaps
        • Setup
        • HTML and CSS files
        • API Key
        • JS Setup
        • Adding Your Location
        • Listeners
        • Custom Options
Powered by GitBook
On this page
  1. 02-DOM-Manipulation

Complete Example

Now let's look at a more complex example, one that uses an input field for the user to enter their name, and then a paragraph where their name is displayed in a sentence.

Build the following HTML:

<body>

    <!--All of our HTML code will go here-->
    <label for="nameInput">Enter Your Name:</label>
    <input type="text" id="nameInput" placeholder="John Smith" />

    <p>Welcome!</p>
    <p>No name has been entered</p>

    <script type="text/javascript">

Now let's write our JavaScript. We want to listen for when a character has been entered into the input field, or when the input field receives a keyup event - the event that fires when a key is released.

<body>

    <!--All of our HTML code will go here-->
    <label for="nameInput">Enter Your Name:</label>
    <input type="text" id="nameInput" placeholder="John Smith" />

    <p>Welcome!</p>
    <p>No name has been entered</p>

    <script type="text/javascript">
        /* All of our JavaScript code will go here */
        document.getElementById('nameInput').addEventListener('keyup', (event) => {
            console.log(event);
        });

    </script>

</body>

Open the website and enter a name into the input field. Now it's time for you to dive into the console, we need to find the current value of the input field - the whole text.

Here we have a test of your investigative skills. Developers often log events to the console and start digging into the unknown trying to search for the answer. They don't know exactly what the answer is, or even if there is one, but there's only one way to find out - and that's to look. Investigate the KeyboardEvent we received, it's up to YOU to find the current value of the input field.

  • If you have not located the answer after 5 minutes, continue to the next step.

Now let's log the current value of the input to the console. Note that your path might be different, the answer is actually in multiple places! Since target is such a common property to use - we'll use that answer.

<script type="text/javascript">
    /* All of our JavaScript code will go here */
    document.getElementById('nameInput').addEventListener('keyup', (event) => {
        console.log(event.target.value);
    });

</script>

If you were unable to find the answer on your own, take a look at the answer above - open up target and then look for the value property.

Open the webpage and put in a sample name - notice the function runs after every keyup, even the shift key! Instead of simply logging the name to the console, we want to display it in the paragraph tag! We do NOT want to create a whole other element inside the paragraph, so innerHTML would be a poor choice... innerText would fit much better.

Since our paragraph tag does not have an ID or a class, we need to select it via the tag, so we'll use getElementByTagName. Go ahead and try it, log the result to the console.

document.getElementById('nameInput').addEventListener('keyup', (event) => {
    console.log(event.target.value);
    console.log(document.getElementsByTagName("p"));
});

Take a look at the console, you will see an HTMLCollection with 2 entries:

Again, now is the time for YOU to dive into the console - it's your job to figure our which entry relates to the "Welcome" paragraph tag, and which one relates to the "No name has been entered" paragraph tag. Do this now. Take no longer than 5 minutes and then proceed to the next section.

Okay, so you should have discovered the first entry relates to the first paragraph tag on the page (the "Welcome" tag)... and the 2nd entry relates to the 2nd paragraph tag on the page. We want to update the 2nd paragraph tag's innerText property to include the value of the input field. Let's make it part of a sentence.

  • *Notice the sentence is written using back ticks (`), not single quote marks. This allows us to use ES-6 string syntax.

    <script type="text/javascript">
      /* All of our JavaScript code will go here */
      document.getElementById('nameInput').addEventListener('keyup', (event) => {
          document.getElementsByTagName("p")[1].innerText = `Everyone please welcome ${event.target.value} to the stage.`;
      });
    </script>

    Test it in the browser and it should work! As soon as you enter a character, the paragraph should update. Lastly, if they were to backspace the name from the input field... we want the text to return to the original "No name has been entered".

    <script type="text/javascript">
      /* All of our JavaScript code will go here */
      document.getElementById('nameInput').addEventListener('keyup', (event) => {
          if (event.target.value === '') {
              document.getElementsByTagName("p")[1].innerText = `No name has been entered`;
          } else {
              document.getElementsByTagName("p")[1].innerText = `Everyone please welcome ${event.target.value} to the stage.`;
          }
      });
    </script>
PreviousEventsNext03-API Fundamentals

Last updated 7 years ago

Input Field
HTML Collection