Form field properties

The form field properties that can be used to access or modify form fields are:

  • disabled : Boolean indicates if field is disabled
  • form : Read only property which pointes to the form.
  • name : Name of field.
  • readonly : Boolean indicates if field is read only.
  • tabIndex : This defines the tab order for the field.
  • type : Indicates the type of field is “text”, “password” …etc.
  • value : Value entered to the form field.

Using DOM elements to modify fields

Like any other DOM elements, form elements such as <input>, <textarea>, <button>, <select>, <fieldset>, can be accessed using its position or name. In the example below, using the DOM elements the first form field can be accessed using: form1.elements[0].value or form1.elements["Name"].value. Using index can lead to error prone results when the order of elements is modified. Instead using id produces more predictable results. When selecting multiple choice fields array index can be used to select them as below form1.elements["color"][0].value.

Example of accesing form elements with JavaScript DOM

JavaScript events on form fields

The events that can be triggered on form fields are:

  • onfocus : Event occurs when value in the field changes
  • onblur : Event occurs when element loses focus
  • onsubmit : Event occurs when form is submitted.
  • onchange : Event occurs when value of a field changes
  • oncontextmenu : Event is triggered when user right-clicks on an element to open context menu.
  • oninput : Event is triggered when an element gets user input.
  • oninvalid : Event is triggered when element is invalid.
  • onreset : Event is triggered when reset button of the form is clicked.
  • onsearch : Event is fired when user is searching a string where <input type = “search”>.
  • onselect : Event is triggered when text is selected in a form field.

The example below shows application of onfocus, onblur, onsubmit, oninput events. 

Example of HTML events in forms and manipulated by JavaScript

 

›› go to examples ››