Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Text Fields

To let the user type something, a page uses the input element, a field to write into. It has no closing tag:

<input id="color">

What's written in the field is in its property value. Usually you read it when the user clicks a button:

const colorInput = document.querySelector("#color");
const showButton = document.querySelector("#show");
const answer = document.querySelector("#answer");

showButton.addEventListener("click", function () {
    answer.textContent = `Your favorite color is ${colorInput.value}.`;
});

Read value inside the handler, at the moment of the click. When the page loads, the field is still empty, so with const color = colorInput.value; at the top of the script, color would always be an empty text, "".

value is always text, even when the user types digits, and even in a field for numbers, <input type="number">. And you know that "40" + 4 is "404". To calculate with the value, turn it into a number with Number():

console.log("40" + 4);         // Prints: 404
console.log(Number("40") + 4); // Prints: 44

If the text isn't a number, for example "hello", Number() returns NaN (Not a Number), a special value that means the text wasn't a number. And an empty field gives Number(""), which is 0.

Instructions

  1. 1

    When reserveButton is clicked, show the text Table reserved for Anna. in reservation, but with the name typed into nameInput instead of Anna. Try it in the page.

  2. 2

    When tipButton is clicked, add a 10% tip to the bill from billInput: the bill plus a tenth of it (the bill divided by 10). Show the result in totalText, for example Total: 44 for a bill of 40.

Back

7/10

  1. 1. JavaScript in a Web Page
  2. 2. Finding Elements
  3. 3. When Nothing Is Found
  4. 4. Changing Styles
  5. 5. Reacting to Clicks
  6. 6. A Click Counter
  7. 7. Text Fields
  8. 8. Creating Elements
  9. 9. Showing an Array
  10. 10. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.