CodingBison

One of the first HTML elements to offer events, an HTML form provides several types of events. These events allow us to handle various form-related tasks like user submitting the form, user changing text in the text input fields etc.

We begin by providing a list of these events along with a short description. Note that the event names begin with the word "on" and all the letters are typically in lower-case; thus, we have "onsubmit" and not "onSubmit".


Table: Form Events
EventDescription
onsubmitwhen we submit the form.
onresetwhen we reset the form.
onselectwhen we select text in the text input fields.
onchangewhen the value of a form element changes.
onfocuswhen we focus a form element.
onblurwhen we take the focus away from a form element.

In the above table, the first event is associated when a user submits an HTML form. The onsubmit event is triggered when the user clicks the submit button of the form. Usually, the submit step sends the form data is sent from data to a server. The onsubmit event provides us an option (via a handler) to potentially process data or to validate data before the data is forwarded to the server.

The next event is that of reset and is triggered when the user clicks the reset button of the form -- with this, all the fields of the form are reset to their original values they had when the form loaded initially. The onreset handler gets invoked before the value of the form fields are restored to their initial values.

The next event is the onselect. This gets triggered when a form element -- typically a text input field or a textarea input field -- is selected.

The fourth event in the above Table is the onchange event. This event gets triggered when we change the value of a form field, which can be a text input field, or a checkbox, or a radio button, or a select field. For text input fields, this means changing the value of the text-value and then moving the focus away from the text input field (either by clicking the mouse outside the text field or using the tab to navigate outside the text input field). The likely reason to wait for the mouse (or the tab) to go outside the text field is to ensure that the user is done changing the value of the input.

The last two events are onfocus and onblur. These events allow us to provide handlers when a form element -- typically text input or textarea input fields -- are focused or when the focus moves away from that element. Note that we can also use these two events for the overall body of the HTML page and so we will revisit these two events in the context of the window-related events as well.

Out of these events, the only cancellable event is that of onsubmit. This means that if the handler to the onsubmit event returns false, then the form would not be submitted to the server. This is a pretty good idea since it is possible that the user may not have input correct data and that for such cases, we can cancel the submission. Of course, we must -- when possible -- alert the user say that the data or its format is not correct, and the user should retry. Since other events are non-cancellable, it would not matter if the handler returns false.

In terms of being able to bubble, all of the events bubble except the following two: onfocus and onblur.

Registering Event Handlers for HTML forms

Let us demonstrate this using a simple HTML form. This form consists of several elements. First, it has a set of checkbox elements that are present to indicate if a given task is completed or not. Second, it has two text element that allow the user to input text for location and notes. The next element is a submit element; this element appears as a button that the user can click once he has provided all the information. The last element is a reset element; this element also appears as a button that the user can click to reset the form back to its initial state.

In this example, we focus on three types of events: onsubmit, onreset, and onchange. The associated object for onsubmit and onreset events is the form element itself and so we add these events to the form tag. The associated object for onchange event can be individual form elements and so in this case, we add onchange event to one of the text input fields. We use addEventListener() to add these different types of options.

 <!doctype html>
 <html>
 <head> <h2> A Wizard Form </h2></head>
 <body> 

 <!-- This provides lightweight CSS design -->
 <style type="text/css">
 .classForm  {border: 2px solid black; border-radius: 12px; padding: 5px; width: 18em;}
 </style>

 <!-- This is a simple HTML form -->
 <form id="idForm"> 
 <div class="classForm">
     <b> Form: To-Do List </b><br>
     Check mark completed tasks: <br>
     <input type="checkbox" id="idCheckboxSpells"> Practice Spells <br>
     <input type="checkbox" id="idCheckboxDragon"> Visit Bilbo Baggins <br>
     <input type="checkbox" id="idCheckboxWand">   Repair broken staff <br> <br>
     Location: <br>
     <input type="text" id="idTextLocation" value="Enter Location"> <br> 
     <input type="submit"   id="idSubmitButton" value="Click to Submit"> 
     <input type="reset"    id="idResetButton" value="Click to Reset"> 
 </div>
 </form>

 <script type="text/javascript">
 function changeToUpperCase() {this.value = this.value.toUpperCase();}
 function alertSubmit() {alert("Need to submit");}
 function alertReset() {alert("Need to reset");}

 function addThisEvent(obj, eventType, eventHandler, capturingType) {
     var newEventType = "on" + eventType;
     if (obj.addEventListener) {
         obj.addEventListener(eventType, eventHandler, capturingType);
     } else if (obj.attachEvent) {
         obj.attachEvent(eventType, eventHandler);
     } else if (obj[newEventType]) {
         obj[newEventType] = eventHandler;
     }
 }

 window.onload = ( function() {
     var elem = document.getElementById("idForm");
     elem.addEventListener("submit", alertSubmit, false);
     elem.addEventListener("reset", alertReset, false);

     elem = document.getElementById("idTextLocation");
     elem.addEventListener("change", changeToUpperCase, false);
 });
 </script>
 <body>
 </html>

If we were to submit the above form, then we would see an alert box saying "Need to submit". Likewise, if were to reset the above form, then we would see an alert box saying "Need to reset".

Lastly, if we were to provide the name of a location in the above location input box, then after we have changed the location input from the provided input text and we move the focus away from that box -- either by moving the mouse outside that text field or by using the tab -- we would find that the provided input would automatically get updated to upper case. Here is the output when we attempt to provide the location, as say, "Middle Earth" and move the focus out of the text input field -- the event handler automatically converts it to all upper-cases.



Figure: Registering Form Events

The above example adds handlers for events like onsubmit, onreset, and onchange. Even for other events, we can use a similar approach. We provide below snippets to do the same (handlerFunction() is the name of the handler function):

 // To add onselect to a text input field.
 elem = document.getElementById("idTextLocation"); 
 elem.addEventListener("select", handlerFunction, false);'.

 // To add onfocus to a text input field.
 elem = document.getElementById("idTextLocation"); 
 elem.addEventListener("focus",  handlerFunction, false);'.

 // To add onblur to a text input field.
 elem = document.getElementById("idTextLocation"); 
 elem.addEventListener("blur",  handlerFunction, false);'.




comments powered by Disqus