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: 44If 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
When
reserveButtonis clicked, show the textTable reserved for Anna.inreservation, but with the name typed intonameInputinstead of Anna. Try it in the page. - 2
When
tipButtonis clicked, add a 10% tip to the bill frombillInput: the bill plus a tenth of it (the bill divided by 10). Show the result intotalText, for exampleTotal: 44for a bill of 40.