如何在输入字段被填充时更改按钮的颜色 - JavaScript?

假设以下是我们的按钮 -

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

在填写下面的输入字段时,上面按钮的颜色应该改变 -

<input type="text" id="changeColorDemo" style="margin-left:10px;margin-top:10px" 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 xx_src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script xx_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>

要运行上述程序,请保存文件名“anyName.html(index.html)”。右键单击该文件,然后在 Visual Studio Code 编辑器中选择“使用 Live Server 打开”选项。

输出结果

这将在控制台上产生以下输出 -

当您在文本框中写入内容时,按钮的颜色将从天蓝色变为绿色,如下所示 -