Overview

This page is a guide to working with HTML form controls through HtmlUnit's plain Java API. It covers three things, in order: the general shape of the form-control classes and the everyday operations you'll use on them; the different, easily-confused ways to read and write a control's value; and the full HTML Constraint Validation API as HtmlUnit implements it.

The form control class hierarchy

Every form control in a parsed page is represented by a subclass of HtmlElement. The two most important base types are:

  • HtmlInput -- the base class for every <input> element, regardless of its type attribute.
  • HtmlSelectableTextInput -- an HtmlInput subclass that adds text-selection and simulated-typing support, used by every text-like input type.

HtmlUnit creates a different concrete class per type attribute value, so that each type can implement exactly the constraints and behavior real browsers give it. The most commonly used ones:

  • HtmlTextInput (type="text", and the default when type is absent or unrecognized)
  • HtmlNumberInput, HtmlEmailInput, HtmlUrlInput, HtmlTelInput, HtmlSearchInput, HtmlPasswordInput -- all text-like, each with its own additional constraint (see Constraint validation below)
  • HtmlCheckBoxInput and HtmlRadioButtonInput -- boolean "checked" controls rather than text controls
  • HtmlFileInput -- represents a file-upload control; see File inputs below
  • HtmlSubmitInput, HtmlResetInput, HtmlButtonInput, HtmlImageInput -- the various button-like input types
  • HtmlHiddenInput -- never a candidate for constraint validation and never focusable, but otherwise a plain value holder
  • HtmlDateInput, HtmlTimeInput, HtmlColorInput, HtmlRangeInput and the other less common HTML5 types each have their own class as well.

Outside the <input> family, HtmlSelect, HtmlTextArea and HtmlButton (the standalone <button> element, not <input type="submit">) are the other major form-control classes; both value handling and validation apply to them too, and are covered later on this page.

If a script changes an input's type attribute at runtime, HtmlUnit internally replaces the Java object backing that DOM node with an instance of the correct class for the new type, carrying the old value across via adjustValueAfterTypeChange() -- each subclass decides for itself what, if anything, of the old value still makes sense under the new type (for example, switching into type="file" always clears the value, since a real browser can never carry a text value over into a file selection).

Finding form controls

The usual DOM-style lookups work as expected -- page.getHtmlElementById(String), page.getElementByName(String), or the generic DomElement traversal/query methods. HtmlForm additionally offers form-scoped convenience lookups that are usually more direct when you already know which form you're working with: