Forms, part two: the controls real sites need
Suggestions as people type, file uploads, numbers and sliders, boxes people may read but not change, the right phone keyboard, and pop-ups with no code at all.
By the end you can
- Suggest answers without forcing a choice, and accept files safely
- Use number boxes and sliders with sensible limits
- Tell readonly from disabled, and know which one still gets sent
- Open a real pop-up and a help bubble without a single library
Easier if you did first
step 1 of 4
Suggestions, and uploading files
A drop-down forces people to pick one of your options. Sometimes that is right. Sometimes you want to suggest, and still let them type something else.
That is <datalist>. Think of a search box that drops hints as you type, but never stops you typing your own words.
You write the suggestions in a <datalist> and give it an id. Then you point an ordinary text box at it with list="that-id". The box stays an ordinary box; the suggestions are only help.
A file upload is <input type="file">. Two attributes make it behave. accept limits what the file picker offers: accept=".pdf,.jpg" or accept="image/*". On a phone, image/* is what makes the camera appear as a choice.
One warning. accept is a convenience, never a lock. Anyone can rename a file, or send data to your site without using a browser at all. Your server has to check the file again when it arrives. The browser is helping honest people, not stopping dishonest ones.
multiple lets someone pick several files at once.
Fix the two boxes on the right.
<label for="service">Service</label>
<input id="service" name="service" list="services" />
<datalist id="services">
<option value="Web design"></option>
<option value="Hosting"></option>
<option value="Security review"></option>
</datalist>
<label for="brief">Attach your brief</label>
<input id="brief" name="brief" type="file" accept=".pdf,.doc,.docx" multiple />What these words mean
- datalist
- A list of suggestions for a text box. People may still type anything.
- list
- On a box: the id of the datalist to take suggestions from.
- type="file"
- A file picker.
- accept
- Which file types the picker should offer.
- multiple
- Allows more than one file to be chosen.
- enctype
- A form that uploads files needs enctype="multipart/form-data" on the form tag.
Easy to get wrong
Trusting accept to keep bad files out
Check the type and the size on the server as well
accept only filters the picker window. The rule only becomes real on your server, which is the one part nobody else controls.
A datalist when the answer must be one of your options
<select>
A datalist accepts anything typed. If your database only knows three values, use a select, or check the answer after it arrives.
What we check
- The service field takes suggestions
- The datalist offers three options
- The input's list matches the datalist's id
- The upload limits which file types are offered
- Several files can be chosen at once