×

javascript · level 2 · unit 4 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Each kind of field hands over its answer in its own way.

<input type="number"> shows a box with little arrows, but its .value is still a string. Wrap it in Number() before doing any maths.

A has no words to read. Its property is true when it is ticked and false when it is not, ready for an if.

A is a <select> holding <option> choices. Its .value is the chosen option's value attribute, so your code gets a tidy name like "large", whatever the label says.

<form id="order">
  <input id="cups" type="number" value="2">
  <select id="size">
    <option value="small">Small (£2)</option>
    <option value="large">Large (£3)</option>
  </select>
  <label><input id="cream" type="checkbox"> Add cream</label>
  <button>Order</button>
</form>
<p id="total"></p>
const cups = document.querySelector("#cups");
const size = document.querySelector("#size");
const cream = document.querySelector("#cream");
document.querySelector("#order").addEventListener("submit", (event) => {
  event.preventDefault();
  let each = 2;
  if (size.value === "large") { each = 3; }
  if (cream.checked) { each = each + 1; }
  document.querySelector("#total").textContent = `Total: £${Number(cups.value) * each}`;
});

Press run it to bring the page to life.

console

nothing logged yet

The <label> tag wraps a checkbox and its words, so clicking the words ticks the box too.