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
Further Reading
Evolution of JavaScript from ES1 to ES2020
Introduction to HTML DOM Methods in JavaScript
Understanding Document Object Model (DOM) in JavaScript
What is Asynchronous JavaScript?
Understanding HTTP Requests and Responses
- AI
- Android
- Angular
- ASP.NET
- Augmented Reality
- AWS
- Bioinformatics
- Biometrics
- Blockchain
- Bootstrap
- C
- C#
- C++
- Cloud Computing
- Competitions
- Courses
- CSS
- Cyber Security
- Data Science
- Data Structures and Algorithms
- Data Visualization
- Datafication
- Deep Learning
- DevOps
- Digital Forensic
- Digital Trust
- Digital Twins
- Django
- Docker
- Dot Net Framework
- Drones
- Elasticsearch
- ES6
- Extended Reality
- Flutter and Dart
- Full Stack Development
- Git
- Go
- HTML
- Image Processing
- IoT
- IT
- Java
- JavaScript
- Kotlin
- Latex
- Machine Learning
- MEAN Stack
- MERN Stack
- Microservices
- MongoDB
- NodeJS
- PHP
- Power Bi
- Projects
- Python
- Quantum Computing
- React
- Robotics
- Rust
- Scratch 3.0
- Shell Script
- Smart City
- Software
- Solidity
- SQL
- SQLite
- Tecgnology
- Tkinter
- TypeScript
- VB.NET
- Virtual Reality
- Web Designing
- WebAssembly
- XML