How To Disable a Button with JavaScript

12/10/2020

Contents

Demo

Full Screen

Video

YouTube Channel

Code

HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>How To Disable a Button with JavaScript</title>
    <link rel="stylesheet" type="text/css" href="https://demo.plantpot.works/assets/css/normalize.css">
    <link rel="stylesheet" href="https://use.typekit.net/opg3wle.css">
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body>
    <div id="container">
      <form class="form">
        <input id="formInput" class="form__input" type="text" name="text" placeholder="Enter Text">
        <button id="formButton" class="form__button" type="button" name="button" disabled="disabled">SUBMIT</button>
      </form>
    </div>
    <script src="script.js"></script>
  </body>
</html>

CSS

@charset "utf-8";
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html {
  font-size: 16px;
}
body {
  font-family: futura-pt, sans-serif;
  -webkit-tap-highlight-color: rgba(0,0,0,0);
}
#container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  padding: 20px;
}
.form {
  width: 100%;
  max-width: 400px;
}
.form__input {
  width: 100%;
  padding: 10px;
  font-size: 1.25rem;
}
.form__button {
  width: 100%;
  margin-top: 10px;
  padding: 10px;
  border: none;
  background-color: #ff749a;
  color: #fff;
  font-size: 1.25rem;
  text-align: center;
  outline: none;
  cursor: pointer;
}
.form__button:disabled {
  background-color: #ccc;
  cursor: default;
}

JavaScript

let formInput = document.getElementById('formInput');
let formButton = document.getElementById('formButton');

formInput.addEventListener('input', () => {
  if(formInput.value.length > 0) {
    formButton.disabled = false;
  } else {
    formButton.disabled = true;
  }
});