[Solved] How to add javascript to HTML?


There are two problems:

  1. You need to include a reference to JQuery.

  2. The <script> requires #textbox in the DOM for it to subscribe to keyup event. Hence the script should be placed at the end of the body. This way #textbox is added to DOM by the time the script runs.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<head></head>

<body>
  <input type="text" id="textbox">

  <script>
    $('#textbox').on('keyup', function(e) {
      var val = this.value;
      
      if (e.which != 8 && e.which != 46) {
        if (val.replace(/\s/g, '').length % 4 == 0) {
          $(this).val(val + ' ');
        }
      } else {
        $(this).val(val);
      }
    })
  </script>
</body>

solved How to add javascript to HTML?