Search code examples
htmlcsstwitter-bootstraptwitter-bootstrap-4

Bootstrap: highlight modified input text?


Is there a built-in way (or a plugin) which highlights input elements which have been modified? As long as the input does not have its original value, the input would be highlighted in some way (e.g. orange border). One could mark all inputs as "unmodified" using JavaScript (e.g., called by my "Save Changes" button).


Solution

  • You can add a change event listener for each input element to add a class.


    (function() {
      var inputs = document.querySelectorAll("input");
    
      for (var i = 0; i < inputs.length; i++) {
        var initialValue = inputs[i].value;
    
        inputs[i].addEventListener("change", function() {
          if (initialValue !== this.value) {
            this.classList.add("changed");
          } else {
            this.classList.remove("changed");
          }
        });
      }
    })();
    .changed {
      background-color: gold;
    }
    <form>
      <input type="text" value="Initial Value">
      <input type="text" value="Initial Value">
      <button type="submit">
        Save Changes
      </button>
    </form>


    If you want to highlight it after submit you can use this class as a selector to add another one with the desired styling.