Web APIs Cheatsheet

Forms and FormData

Use this Web APIs reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Accessing Form Elements

const form = document.getElementById('signup');   // HTMLFormElement

// Access controls by name (live HTMLFormControlsCollection)
form.elements['email'];           // input[name="email"]
form.elements.email;              // same
form.email;                       // shorthand (avoid — conflicts with methods)
form.elements[0];                 // first control by index
form.elements.length;

// From a control back to its form
input.form;                       // parent HTMLFormElement or null

Form Properties and Methods

Property / MethodDescription
form.actionForm submission URL
form.method'get' or 'post'
form.enctype'application/x-www-form-urlencoded' | 'multipart/form-data' | 'text/plain'
form.noValidateSkip browser validation
form.autocomplete'on' | 'off'
form.elementsLive HTMLFormControlsCollection
form.lengthNumber of controls
form.submit()Submit without firing submit event
form.requestSubmit(submitter?)Submit and fire submit event
form.reset()Reset all controls to default
form.checkValidity()true if all controls are valid
form.reportValidity()Check + show browser validation UI

Submit Event

form.addEventListener('submit', async e => {
  e.preventDefault();              // prevent page navigation

  // Read values
  const data = new FormData(form);
  const email = data.get('email');

  // Or as object
  const obj = Object.fromEntries(data);

  await fetch('/api/signup', { method: 'POST', body: data });
});

Input Element Properties

PropertyTypeNotes
el.valuestringCurrent value
el.defaultValuestringOriginal HTML value
el.typestring'text' 'email' 'checkbox' 'file'
el.namestringForm field name
el.idstringElement id
el.placeholderstring
el.requiredboolean
el.disabledbooleanExcluded from form data
el.readOnlybooleanNot editable but included in data
el.autofocusboolean
el.autocompletestring
el.checkedbooleancheckbox / radio
el.defaultCheckedbooleanOriginal checked state
el.indeterminatebooleanTri-state checkbox (visual only)
el.multipleboolean<select> / <input type="file">
el.filesFileListtype="file" only
el.selectedIndexnumber<select>
el.optionsHTMLOptionsCollection<select>
el.min / el.maxstringnumber / date / range inputs
el.stepstring
el.maxLengthnumber
el.minLengthnumber
el.patternstringRegex for type="text" etc.
el.selectionStart / el.selectionEndnumberText selection range

Reading Values by Input Type

// Text, email, password, url, search, tel
input.value;

// Checkbox
input.checked;

// Radio group — find the selected one
const selected = form.elements['color'].value; // or
[...form.elements['color']].find(r => r.checked)?.value;

// Select (single)
select.value;
select.selectedIndex;
select.options[select.selectedIndex].text;

// Select (multiple)
[...select.selectedOptions].map(o => o.value);

// File
const file = input.files[0];
const files = [...input.files]; // convert FileList

// Date / time (always a string)
input.value;         // '2025-12-31'
new Date(input.value);

// Range / number
Number(input.value);

// Color
input.value;         // '#ff0000'

// Textarea
textarea.value;
textarea.rows; textarea.cols;

FormData API

// From form element
const fd = new FormData(form);

// Manual
const fd = new FormData();
fd.append('username', 'alice');
fd.append('files', file1);
fd.append('files', file2);     // multiple values for same key

// Methods
fd.get('username');            // first value for key
fd.getAll('files');            // array of all values for key
fd.set('username', 'bob');     // replace all values for key
fd.delete('username');
fd.has('email');               // boolean
fd.append('blob', new Blob(['hello'], { type: 'text/plain' }), 'file.txt');

// Iterate
for (const [key, value] of fd) { /* … */ }
fd.forEach((value, key) => { /* … */ });
[...fd.keys()];
[...fd.values()];
[...fd.entries()];

// Convert to plain object (single values only — loses multiple)
Object.fromEntries(fd);

// Send — browser sets Content-Type: multipart/form-data with boundary
await fetch('/upload', { method: 'POST', body: fd });

Constraint Validation API

// Per-input
input.validity;               // ValidityState object
input.validationMessage;      // browser-generated message string
input.checkValidity();        // boolean; fires 'invalid' event if false
input.reportValidity();       // check + show tooltip

// ValidityState properties (all boolean)
input.validity.valueMissing;    // required but empty
input.validity.typeMismatch;    // wrong type (e.g. email without @)
input.validity.patternMismatch; // pattern attribute not matched
input.validity.tooShort;        // minlength not met
input.validity.tooLong;         // maxlength exceeded
input.validity.rangeUnderflow;  // below min
input.validity.rangeOverflow;   // above max
input.validity.stepMismatch;    // not a valid step
input.validity.badInput;        // cannot be converted
input.validity.customError;     // setCustomValidity was called
input.validity.valid;           // all constraints pass

// Custom error message
input.setCustomValidity('Username is taken'); // sets customError
input.setCustomValidity('');                  // clear custom error

// Styling
// :valid, :invalid, :user-valid, :user-invalid CSS pseudo-classes
// Custom validation on submit
form.addEventListener('submit', e => {
  const pw = form.elements['password'];
  const confirm = form.elements['confirm'];
  if (pw.value !== confirm.value) {
    confirm.setCustomValidity('Passwords do not match');
    confirm.reportValidity();
    e.preventDefault();
    return;
  }
  confirm.setCustomValidity('');
});

Select, Option, and Datalist

const select = document.querySelector('select');

// Add option
select.add(new Option('Label', 'value', false, true)); // (text, value, defaultSelected, selected)
select.options[select.options.length] = new Option('New', 'new');

// Remove option
select.remove(0);                // by index
select.options[0].remove();

// Programmatic select
select.value = 'option-value';
select.selectedIndex = 2;

// Datalist (autocomplete suggestions, not a select)
// <input list="browsers"> + <datalist id="browsers">
// No special JS API — just add <option> elements to the datalist

Reset and Default Values

form.reset();                     // all inputs go to defaultValue / defaultChecked
input.defaultValue = 'initial';   // set the reset-to value
checkbox.defaultChecked = true;

// Programmatic reset of one field
input.value = input.defaultValue;

File Input

const input = document.getElementById('file-input'); // <input type="file">

input.addEventListener('change', () => {
  const file = input.files[0];
  file.name;        // 'photo.jpg'
  file.size;        // bytes
  file.type;        // 'image/jpeg'
  file.lastModified; // ms timestamp

  // Read contents
  const url = URL.createObjectURL(file);  // temporary blob URL
  img.src = url;
  URL.revokeObjectURL(url);               // release when done

  // FileReader (event-based)
  const reader = new FileReader();
  reader.onload = e => console.log(e.target.result);
  reader.readAsDataURL(file);     // base64 data: URL
  reader.readAsText(file, 'utf-8');
  reader.readAsArrayBuffer(file);

  // Modern: File / Blob .text() / .arrayBuffer() / .stream()
  const text = await file.text();
  const buffer = await file.arrayBuffer();
  const stream = file.stream();  // ReadableStream
});

Programmatic Form Submission

// Submit with Enter key on a button
form.requestSubmit();           // fires 'submit', runs validation

// Submit via specific submit button (sets submitter in event)
form.requestSubmit(document.getElementById('save-btn'));

// Bypass validation
form.noValidate = true;
form.submit();                  // does NOT fire 'submit' event

Common Patterns

// Controlled input (sync state)
let value = '';
input.addEventListener('input', e => {
  value = e.target.value;
  render(); // update UI
});

// Debounced search
let timer;
searchInput.addEventListener('input', e => {
  clearTimeout(timer);
  timer = setTimeout(() => search(e.target.value), 300);
});

// Serialize form to JSON (flat, single values)
const payload = Object.fromEntries(new FormData(form));

// Serialize with arrays (all multi-value keys preserved)
function serializeForm(form) {
  const fd = new FormData(form);
  const out = {};
  for (const key of new Set(fd.keys())) {
    const vals = fd.getAll(key);
    out[key] = vals.length === 1 ? vals[0] : vals;
  }
  return out;
}