The following code demonstrates an Example of handling onChange Event in JavaScript.

In fact, we can manipulate the style of an element using JavaScript. In order to do that, first we need to retrieve that element. We can do it by using the Id attribute of that element. After that we can set a specific style property as given in the following example.

The following example demonstrates handling onchange event. When user selects an item from the dropdown list, onchange event fires. Further, the function f1() is called. The selectedIndex property returns the index of the item that user selects. Similarly, the value property returns its value. Hence, the variable newcolor gets the value of color selected by the user. After that, the background color of div is set to newcolor.

<html>
  <head>
    <title>JavaScript Events</title>
    <script>
      function f1(colors)
      {
         var v=document.getElementById("d1");
         var newcolor=(colors.options[colors.selectedIndex].value);
         //document.bgColor=newcolor;
         v.style.backgroundColor=newcolor;
      }
    </script>
    <style>
       div{
         margin: 100px;
         width: 300px;
         height: 200px;
         border: 2px black solid;
        }
    </style>
  </head>
  <body>
     <select name="s1" onchange="f1(this)">
        <option value="red" selected>Red</option>
        <option value="blue">Blue</option>
        <option value="green">Green</option>    
     </select>
     <div id="d1"></div>
  </body>
</html>

Output

Demonstrating an Example of handling onChange Event in JavaScript
Demonstrating an Example of handling onChange Event in JavaScript

Further Reading

Evolution of JavaScript from ES1 to ES2020

Introduction to HTML DOM Methods in JavaScript

JavaScript Practice Exercise

Understanding Document Object Model (DOM) in JavaScript

What is Asynchronous JavaScript?

Understanding JSON Web Tokens

Arrow Functions in JavaScript

Understanding HTTP Requests and Responses

Princites