user9077699
user9077699

Reputation:

event.preventDefault doesn't work properly

I'm currently working on a bot, nothing too fancy. Just some basic bot and the thing is that whenever I type google for example it refreshes the page even though I put two event.preventDefault(). And when somehow I fix this it opens two tabs (when google is typed) so I'm really confused about the problem.

JavaScript:

var INPUT = document.getElementsByTagName("input")[0];
INPUT.addEventListener("keyup", function(event) {
  event.preventDefault();
  if (event.keyCode === 13) {
    document.forms[0].submit();
  }
});

function requester(event) {
  event.preventDefault();
  var valeur = (document.getElementsByTagName("input")[0].value).toString().trim().toLowerCase();
  switch (valeur) {
    case "date": date(); break;
    case "day": day(); break;
    case "hour": hour(); break;
    case "stop": stopTime(); break;
    case "youtube": open("https://www.youtube.ca"); break;
    case "google": open("https://www.google.ca"); break;
    case "chrono": chrono(); break;
    case "refresh": location.reload(); break;
    case "my_playlist": open("https://www.youtube.com/playlist?list=PLjhkALRcmTGR2MQ-Y5cMERhq15ieGOqBR"); break;
  }
}

HTML:

<form onsubmit="requester(event)">
  <input type="text" autocomplete="off" style="font-size:150px;text-transform: uppercase;" autofocus>
</form>

Upvotes: 2

Views: 114

Answers (1)

user149341
user149341

Reputation:

document.forms[0].submit() doesn't fire a submit event:

When invoking this method directly, no submit event is raised (in particular, the form's onsubmit event handler is not run), and constraint validation is not triggered either.

(from the MDN documentation for HTMLFormElement.submit())

Additionally, default form submission is triggered by keydown, not keyup.

Two easy solutions:

  1. Remove the keyup handler. Pressing Return in a form field will fire a submit event by default; you don't need to implement anything additional.

  2. Alternatively, if you really want to have a keyboard handler, bind the handler to keydown, and call requester directly instead of calling .submit().

Upvotes: 2

Related Questions