Form handling onsubmit, onchange, onselect, onblur, onfocus

Site: Philippine Science High School - MC - Knowledge Hub
Course: SY25.CS3.Web Development
Book: Form handling onsubmit, onchange, onselect, onblur, onfocus
Printed by: , Guest user
Date: Friday, 27 February 2026, 7:46 PM

1. Introduction

After completing this module, you are expected to:

  • Design a simple form as user information input
  • Create a dynamic web form

          Last quarter, we learned about events where certain actions are triggered when certain events happen on a web page. These events are tested in the JS code through the use of event handlers and one example is onclick. This is used to call a block of JS code to be executed when an HTML element is clicked.

          In this module, we will discuss other  event handlers that can be used to make websites more interactive. We will focus particularly on event handlers that are applicable to HTML forms. By adding event handlers to HTML forms, we can engage the user more and we can process the data provided by the user. Processing data from forms and input elements is called form handling. Alongside these HTML event handlers, we will also learn about the different ways that input from forms can be handled for processing using JS.

          This learning guide will discuss five different event handlers to track user actions. Processing of values from forms will also be demonstrated in the sample codes.

2. onsubmit

         Using this event handler will execute an action when the user clicks on the submit button. Let’s look at the code below for its  sample use. Using onsubmit calls a JS function myFunction()and prints the entered username.

          This code will also demonstrate how JS retrieves the input of the user from the textbox and uses that input for processing in JavaScript. The value property is used to get the value entered by the user in the input element. Remember how we used the innerHTML property to indicate the contents of an HTML element? The concept of value works the same way.

 <form onsubmit="return myFunction();">

<label for="uname">Username: </label>

<input type="text" id="uname">

<input type="submit">

</form>

<p id="demo">

</p>

<script>

    function myFunction(){

        var x = document.getElementById("uname").value;

        document.getElementById("demo").innerHTML = "Your input is " + x + ".";  

        return false;

  }

</script>

 

          Notice the use of return in calling the function from the onsubmit attribute and the return false line at the end of the function. We use a return value to help the onsubmit event handler determine what to do with the form. If the return value is true, the value from the form is sent to a server for processing and the server replies back. In our example, we are only dealing with client-side processes so we are returning false to make the browser stay on the current page and instruct the webpage to not send the values to a server. If you try to remove the return in the function, you will see that the desired display shows for a brief moment and then disappears. By adding a return false to out script, the browser will stay on the current page.


2.1. Retrieving the values from checkboxes using value and onsubmit

          The code snippet below shows another example of using onsubmit and value to retrieve values from the user for processing in the JavaScript code. This example uses a set of checkbox options that have the same name. The JavaScript code retrieves all options using getElementsByName() and loops through all options in the checkbox set and checks each option if they are checked. When the item is checked, it is added to a string to be alerted.

 <form onsubmit="return myFunction();">

    <h2> Add-ons for my milktea </h2>

    <input type="checkbox" id="creamCheese" name="choices" value="Cream Cheese">

    <label for="creamCheese"> Cream Cheese</label><br>

    <input type="checkbox" id="pearls" name="choices" value="Pearls">

    <label for="pearls"> Pearls </label><br>

    <input type="checkbox" id="coffeeJelly" name="choices" value="Coffee Jelly">

    <label for="coffeeJelly"> Coffee Jelly</label><br><br>

    <input type="submit"></input>

</form>

<script>

    function myFunction(){

        var x ="";

        var choices = document.getElementsByName("choices");

        for (var i=0; i<choices.length; i++){

            if (choices[i].checked){

                x = x + choices[i].value + " ";

            }

        }

        alert("You have chosen " + x);

        return false;

    }

</script>




3. onchange

          This is used to detect changes in value of form elements.

          The example below shows a code where a function myFunction() is called when the user changes the value of their input in the textbox. When the user changes their input in the textbox, the new value is printed. When the user presses enter but the value in the textbox has not changed, no action is executed.

<form>

<label for="uname">Username: </label>

<input type="text" value="Type here" id="uname" onchange="myFunction()">

</form>

<p id="demo"></p>

 <script>

function myFunction() {

  var x = document.getElementById("uname").value;

  document.getElementById("demo").innerHTML = "The value is changed! The new value is: " + x;

}

</script>

          Another example is shown below on how the onchange event handler is used. This time, instead of a textbox, a selection element is used. A function is triggered whenever the user changes their choice.  Notice that the value property also works in retrieving the input from a select element.

<form>

<select id="selection" onchange="myFunction()">

       <option value="Coffee">Coffee</option>

      <option value="Tea">Tea</option>

      <option value="Juice">Juice</option>

</select>

</form>

<p id="demo"></p>

<script>

function myFunction() {

var x = document.getElementById("selection").value;  

document.getElementById("demo").innerHTML = "Your new choice is " + x + ".";

}

</script>


4. onselect

onselect is used to track when a user selects/highlights a text inside an input element or a textarea.

The code below is an example of the use of onselect. When the user selects any text inside the textarea, the function myFunction() is called.

 

<form>
           <label style="valign:middle" for="comment">Comments</label>
           <textarea id="comment" onselect="myFunction()" cols="50" rows="10"> </textarea>
</form>
<script>
     function myFunction() {
             var txtArea = document.getElementById("comment");
             var selectedText;   
             if (txtArea.selectionStart != undefined) {    
                  var startPosition = txtArea.selectionStart;
                  var endPosition = txtArea.selectionEnd;
                  selectedText = txtArea.value.substring(startPosition, endPosition);
             }
             alert("You selected : " + selectedText);
     }
</script>


5. onblur

          The onblur event handler is used to track a user going away from an input element. “Goes away” means that the user may have clicked away, scrolled away, or clicked on other input elements. It is mainly used for checking if the input from the user is valid. One example is when you want to make sure that the user will input a value in a textbox. When the user clicks outside of the textbox, you can use this event to alert or display a pop-up that informs the user that they are required to input a value.

          The example below shows a code where a function is executed when the user clicks away from the text box. The user is alerted to go back to the textbox if the value is empty, else, the user is alerted

<form>

<label for="inpt">Type here: </label>

<input type="text" id="inpt" onblur="myFunction()">

</form>

<p id="demo"></p>

<script>

function myFunction() {

     var x = document.getElementById("inpt").value;

     if (x == ""){

                  alert("Go back to the textbox!");

            }

            else{

alert("Value accepted.");

}

}

</script>


6. onfocus

          When onblur tracks the going away of a user from an input element, onfocus tracks the opposite. onfocus, as the name implies, is when a user focuses on a form element. Focusing could mean clicking on the form element or selecting it.

          The example below shows a code with a textbox and the code uses the onfocus and onblur function together in a single element to create an interaction with the user. When onfocus is triggered, the width of the textbox is increased. When onblur is triggered, the width of the textbox is decreased and if there is no value in the textbox, the user is alerted to enter a value.

 <form>

<label for="uname">Username: </label>

<input type="text" id="uname" onfocus="myFunction1()" onblur="myFunction2()">

</form>

 <script>

function myFunction1() {

document.getElementById("uname").style.width = "100px";

}

function myFunction2() {     

var x = document.getElementById("uname");

       x.style.width = "50px";

       if (x.value == ""){

            alert("Please enter a value!");

      }

}

</script>


7. Summary and References

Summary

Form handling is the processing of forms for interaction with the user and retrieval of the inputted values for a server or a JavaScript code to use. By using HTML events and its corresponding event handlers, we can track actions done by the user to trigger a function or other events to process the values from the user. The event handlers that we have discussed for this module are onsubmit, onselect, onchange, onfocus, and onblur.

References

W3Schools. (n.d.). onchange Event. Retrieved from w3schools.com: https://www.w3schools.com/jsref/event_onchange.asp

W3Schools. (n.d.). HTML onchange Attribute. Retrieved from w3schools.com: https://www.w3schools.com/tags/att_onchange.asp

W3Schools. (n.d.). HTML onselect Event Attribute. Retrieved from w3schools.com: https://www.w3schools.com/tags/ev_onselect.asp

W3Schools. (n.d.). onselect Event. Retrieved from w3schools.com: https://www.w3schools.com/jsref/event_onselect.asp

W3Schools. (n.d.). onblur Event. Retrieved from w3schools.com: https://www.w3schools.com/jsref/event_onblur.asp

W3Schools. (n.d.). HTML onblur Event Attribute. Retrieved from w3schools.com: https://www.w3schools.com/tags/ev_onblur.asp

MDN Contributors. (2021, February 20). GlobalEventHandlers.onselect. Retrieved from MDN Web Docs: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onselect

isolani. (n.d.). Simple Javascript and Forms. Retrieved from isolani.co.uk: http://isolani.co.uk/articles/simpleJavascriptAndForms.html