Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Thay đổi màu nút khi ô nhập liệu được điền - JavaScript

Giả sử chúng ta có nút sau:

<button id="buttonDemo" style="background:skyblue;margin-left:10px;">Press Me</button>

Khi điền vào ô nhập liệu bên dưới, màu nút trên sẽ thay đổi:

<input type="text" id="changeColorDemo" style="margin-left:10px;margin-top:10px" onkeyup="changeTheColorOfButtonDemo()">

Ví dụ

Mã hoàn chỉnh:

<!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>

Để chạy chương trình, lưu file index.html và mở với Live Server trong VSCode.

Kết quả

Khi gõ chữ vào ô input, nút chuyển từ xanh dương sang xanh lá. Khi xóa trắng, nút quay lại xanh dương.