ปุ่ม: <button id="buttonDemo" style="background:skyblue;margin-left:10px;">Press Me</button>
ช่อง input: <input type="text" id="changeColorDemo" onkeyup="changeTheColorOfButtonDemo()">
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<body>
<label>UserName: </label>
<input type="text" id="changeColorDemo" style="margin-left:10px;margin-top:10px" onkeyup="changeTheColorOfButtonDemo()">
<br><br>
<button id="buttonDemo" style="background:skyblue;margin-left:10px;">Press Me</button>
</body>
<script>
function changeTheColorOfButtonDemo() {
if (document.getElementById("changeColorDemo").value !== "") {
document.getElementById("buttonDemo").style.background = "green";
} else {
document.getElementById("buttonDemo").style.background = "skyblue";
}
}
</script>
</html>บันทึกเป็น index.html เปิดด้วย Live Server
ผลลัพธ์
ปุ่มสีฟ้าอ่อน → พิมพ์ในช่อง input → ปุ่มกลายเป็นสีเขียว
ล้างช่อง input → ปุ่มกลับสีฟ้าอ่อน


คำอธิบาย: event onkeyup เรียกฟังก์ชันทุกครั้งที่ปล่อยปุ่มตรวจสอบ value !== "" เปลี่ยน style.background
แนวทางปัจจุบัน: ใช้ addEventListener('input', ...) แทน onkeyup จะจับการ paste ด้วย