Drop-Down Lists and Checkboxes

Instead of typing, the user often just chooses. A drop-down list is the select element, with an option element for each choice:

<select id="drink">
    <option value="tea">Tea</option>
    <option value="coffee" selected>Coffee</option>
    <option value="juice">Juice</option>
</select>

The text between the tags is what the user sees, and the value attribute is what your script gets: the value of the select is the value of the chosen option. When the page loads, that's "coffee", because the attribute selected chooses its option in advance. As with a text field, the value is always text.

A checkbox is an input with type="checkbox":

<input id="sugar" type="checkbox">
<label for="sugar">With sugar</label>

The label element is the text that belongs to a field. Its for attribute holds the field's id, so a click on the text ticks the box too. Whether the box is ticked is in its property checked: true or false. Don't use value here: the value of a checkbox is the text "on", ticked or not.

When the user chooses another option, or ticks or unticks the box, the element gets the event change:

const drinkSelect = document.querySelector("#drink");
const sugarCheckbox = document.querySelector("#sugar");
const order = document.querySelector("#order");

function showOrder() {
    if (sugarCheckbox.checked) {
        order.textContent = `Your order: ${drinkSelect.value} with sugar`;
    } else {
        order.textContent = `Your order: ${drinkSelect.value}`;
    }
}

drinkSelect.addEventListener("change", showOrder);
sugarCheckbox.addEventListener("change", showOrder);

Both elements run the same function, and it reads both of them, so the order always matches what's chosen, whichever of them has changed. sugarCheckbox.checked is already true or false, so it can be the condition by itself.

Text fields get change too, but only once the user is done: when they leave a field whose text they've changed, or press Enter in it. To react while they type, use input.

Instructions

Write a function showPrice() that shows the price of the chosen size in priceText, for example Price: €13 for a large pizza. Make it the change handler of sizeSelect.

Extra cheese costs €2: in showPrice(), add 2 to the price when cheeseCheckbox is checked. The value of sizeSelect is text, so turn it into a number first. Make showPrice() the change handler of cheeseCheckbox too. A large pizza with extra cheese then shows Price: €15.

Start programming for free

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

Or sign up with:

Back

5/10

Next