แอตทริบิวต์ HTML onchange จะทำงานเมื่อคุณเปลี่ยนค่าขององค์ประกอบ HTML ในเอกสาร HTML
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์ -
<tagname onchange=”script”></tagname>
ตัวอย่าง
ให้เรามาดูตัวอย่าง HTML onchange event Attribute -
<!DOCTYPE html>
<html>
<head>
<style>
body {
color: #000;
height: 100vh;
background-color: #FBAB7E;
background-image: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%);
text-align: center;
padding: 20px;
}
.show {
font-size: 1.1rem;
margin: 1rem auto;
}
select {
height: 2rem;
width: 30%;
font-size: 1rem;
background: transparent;
border: 2px solid #fff;
outline: none;
}
</style>
</head>
<body>
<h1>HTML onchange Event Attribute Demo</h1>
<p>Select your favourite subject:</p>
<select onchange="get()">
<option>Physics</option>
<option>Chemistry</option>
<option>Maths</option>
</select>
<div class="show"></div>
<script>
function get() {
var msg = document.querySelector('.show');
msg.innerHTML = "Current Value is " + document.querySelector("select").value;
}
</script>
</body>
</html> ผลลัพธ์

ตอนนี้ให้เปลี่ยนค่าของ drop-drow list เพื่อดูว่าเหตุการณ์ onchange ถูกทริกเกอร์อย่างไร
