Drop-Down Lists and Radio Buttons

Some questions have only a few answers: which drink, which size. For those, forms have drop-down lists (select) and radio buttons, and v-model works on both.

A select has an option for each answer. The text of an option is what the customer sees, and its value is what goes into the ref when they choose it:

<select v-model="drink">
    <option disabled value="">Choose a drink</option>
    <option value="Espresso">Espresso, €2</option>
    <option value="Green Tea">Green Tea, €3</option>
</select>

With const drink = ref("");, the list starts at the first option, whose value is "". It's disabled, so the customer can't choose it: it's only there to say what to do. Choose Green Tea, and drink is "Green Tea". And it's two-way, as always: drink.value = "Espresso" in the script chooses Espresso in the list.

The options can come from an array, with v-for. Their values then come from the data too, with :value:

<option v-for="item in menu" :key="item.id" :value="item.name">
    {{ item.name }}, €{{ item.price }}
</option>

Radio buttons are inputs with type="radio", one for each answer, and only one of them can be checked. Give each its own value and all of them the same v-model, and the ref gets the value of the checked one:

<label>
    <input type="radio" value="small" v-model="size">
    Small
</label>
<label>
    <input type="radio" value="large" v-model="size">
    Large
</label>

With const size = ref("small");, Small starts checked. A label around an input makes its text clickable too.

Typical mistake:

  • A ref that isn't the value of any option. With ref("green tea") and value="Green Tea", the list shows no option at all until the customer chooses one: uppercase and lowercase letters matter, as they do with ===.

Instructions

  1. Fill the drop-down list #drink with an option for each drink of menu: its name and price as the text, like Cappuccino, €3, and its name as the value. Connect the list with drink.

  2. Give the radio buttons the values small, medium and large, and connect them with size. Medium is checked at the start.