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

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.

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.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

7/10