Optimal website interactivity creates a positive effect on user. Adding form events smartly, results in a rich user experience. So, how to create an interactive form? Interactive forms includes features like:
There are many ways to use form events, let's see some mostly used ones:
onfocus event handler, you can change element's style like change color, add shadow, etc. Similarly, you can show tooltips or alert boxes to give information about the input field.
In the example below, when user focuses, i.e., clicks on the input field, its color changes to green from white. So, what really happens is that when user clicks on input field, the onfocus event gets trigerred. The
onfocus handler takes the control and calls the user-defined
highlightInput() function. This function has the code to change the input field's color to green. Function executes and changes input field's color.
Note: The value of this keyword inside an event handler refers to the element which has the handler on it. In the example above, it refers to the input field under focus.
onblur event handler is used to handle this event.
In the example of onblur event, an alert box gets displayed to inform the user that the input field has loses its focus. Notice that in this example the event handler is not calling any user-defined function. It is calling JS's in-built
alert() function because we just want to give textual information to the user.
You are free to experiment with the code. Make your functions and try different styles.
Note: First click inside the text input box then click outside to see how it works.
onchange event handler is used to handle this event.
In the example of
onchange event, a selection list is created. When the user changes the default value of the selection list, the
onchange event handler gets trigerred and calls the alert box, as defined in the code. The alert box confirms the selection.
Note: Select any option in select box to see how it works.
onsubmit event handler is used to handle this event.
The example of onsubmit event also has an alert box popup. The
onsubmit event handler gets trigerred when user clicks on the submit button. The alert box warn users that the information entered by them will be submitted to the online server. Try it out.