DreamBlack DreamBlack - 1 month ago 23
HTML Question

How to add javascript to HTML?

Today i was trying to add this to html file but don't work

<head><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);
}
})</head></script>
<body>
<input type="text" id="textbox">
</body>


Can anyone help me? thanks anyway

Answer Source

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>