← Web basics: HTML, CSS and JavaScript

Buttons and required fields

Submit buttons, required, and helpful hints.

Start this lesson

A form needs a way to send it: a <button> inside the form. A button inside a form submits it by default (type="submit"). Use type="button" for buttons that should only run JavaScript and not send anything. Add the required attribute to fields that must be filled in; the browser then refuses to submit and points to the empty field, with no code needed. Small helper text, like "We never share your number", can go in a paragraph near the field.

<form>
  <label for="nick">Nickname</label>
  <input id="nick" name="nick" required>

  <label for="age">Age</label>
  <input id="age" name="age" type="number" min="13">

  <button type="submit">Create account</button>
</form>

Nickname is required, age is optional. Pressing "Create account" (or Enter) tries to submit; if the nickname is empty, the browser shows a message and stops.

Button text should say what happens: "Create account", "Send message", "Book table". "Submit" works but tells people less.

Browser checks are a convenience for the visitor. Real websites still check the data again on the server, because anyone can bypass the browser.