CodeBlanks Logo Icon CodeBlanks

UI and city input

JavaScript course · Intermediate · Lesson 91/134

Set up city input with input and button and bind the click event.

Reading the input value

We read the text of an input field through the input.value property. It is both a getter and a setter: assigning to it clears the field. We'll define a getWeather function. The function reads the city name with cityInput.value and logs it with console.log. Then we bind this function to the button's click event with getWeatherButton.addEventListener("click", getWeather). We pass the function without parentheses; the browser calls it.

Listening for clicks

To listen for a button's click we use the addEventListener method. The first parameter is the event type ("click"), the second is the function to call. The call getWeatherButton.addEventListener("click", getWeather) runs the getWeather function on every click. We pass the function without parentheses (getWeather, not getWeather()). With parentheses the function would run immediately; we instead let the browser call it. This pattern is called a callback.

Exercise Define getWeather and bind it to the button

Continue on top of the previous lesson's solution. Write a getWeather function: read the city name with cityInput.value into a city variable and log it with console.log(city). Then bind it to the button with getWeatherButton.addEventListener("click", getWeather).

Show example solution
const app = document.querySelector("#app");
const cityInput = document.querySelector("#cityInput");
const getWeatherButton = document.querySelector("#getWeatherButton");
const weatherResult = document.querySelector("#weatherResult");
console.log(app, cityInput, getWeatherButton, weatherResult);

function getWeather() {
  const city = cityInput.value;
  console.log(city);
}

getWeatherButton.addEventListener("click", getWeather);

Test yourself

  1. What does cityInput.value return?

    const city = cityInput.value;
    • The input's placeholder text
    • The input's HTML content
    • The text the user typed
    • The input's id
    Show answer

    The text the user typed — Correct! value gives the text the user typed.

  2. Read the input value

    const city = ____;
    Show answer
    const city = cityInput.value;
  3. Match the method to its purpose

    cityInput.value
    Reads the typed text
    addEventListener
    Listens for an event
    console.log
    Writes to the screen
    function
    Defines a function
  4. Match the getWeather steps

    cityInput.value
    Reads the city
    console.log
    Writes to the screen
    addEventListener
    Binds the click

All lessons in Intermediate