Search code examples
htmlformsinputbootstrap-5highlight

Bootstrap highlight empty input/field in form


I have an "Update Profile" form. I would like to highlight empty inputs which are not required but "nice to have" for users to fill in.

Is it possible to highlight them if the input fields are empty (some sort of glow similar to the active field below or some other highlighting method)?

See example here:

Glow when active input field

.form-control:focus {
   border-color: #FF0000;
   
}
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://getbootstrap.com/docs/5.3/assets/css/docs.css" rel="stylesheet">
    <title>Bootstrap Example</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  </head>
  <body class="p-3 m-0 border-0 bd-example">

    <!-- Example Code -->
    
    <div class="input-group mb-3" bis_skin_checked="1">
      <span class="input-group-text" id="inputGroup-sizing-default">Default</span>
      <input type="text" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default">
    </div>
    
    
    <!-- End Example Code -->
  </body>
</html>


Solution

  • You can make those inputs required.

    input:not(:valid) {
        background-color: yellow;
    }
    First Name <input type="text" required><br>
    Last Name <input type="text" required>

    You can do it with Javascript and then you do not need to make them required:

    addEventListener("load", function() {
        let preferredElements = document.getElementsByClassName("preferred");
        for (let preferred of preferredElements) {
             preferred.addEventListener("input", function() {
                 preferred.classList[preferred.value ? "remove" : "add"]("highlighted");
             });
             preferred.classList[preferred.value ? "remove" : "add"]("highlighted");
        }
    });
    .highlighted {
        background-color: yellow;
    }
    <input name="a" class="preferred" type="text"><br>
    <input name="b" class="preferred" type="text">