Theo E
Theo E

Reputation: 77

How do I trigger a key event with javascript?

I have the following input that I want to display an alert when the enter key is pressed. The input id changes on each page load, so I would like to use some of the other attributes, such as the name. I tried the following code, but it does not work.

$('input[name="tmp_post_tag"]').keypress(function(event) {
  var keycode = (event.keyCode ? event.keyCode : event.which);
  if (keycode == '13') {
    alert('You pressed a "enter" key in textbox');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="cred_form_1046_1-textfield-6-1538886027" name="tmp_post_tag" value="" data-taxonomy="post_tag" class="wpt-new- 
    taxonomy-title js-wpt-new-taxonomy-title form-control wpt-form- 
    textfield form-textfield textfield" data-wpt-type="textfield" data-wpt- id="cred_form_1046_1_cred_form_1046_1-textfield-6-1538886027" data-wpt- name="tmp_post_tag" autocomplete="off" type="text">

Thanks in advance.

Upvotes: 0

Views: 324

Answers (1)

Leogao
Leogao

Reputation: 314

Just import Jquery library into the HTML. It should work. And I paste the whole code as following. hope it will help you.

<!DOCTYPE html>
<html>

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

<body>
  <input id="cred_form_1046_1-textfield-6-1538886027" name="tmp_post_tag" value="" data-taxonomy="post_tag" class="wpt-new- 
    taxonomy-title js-wpt-new-taxonomy-title form-control wpt-form- 
    textfield form-textfield textfield" data-wpt-type="textfield" data-wpt- id="cred_form_1046_1_cred_form_1046_1-textfield-6-1538886027" data-wpt- name="tmp_post_tag" autocomplete="off" type="text">
  <script>
    $('input[name="tmp_post_tag"]').keypress(function(event) {
      var keycode = (event.keyCode ? event.keyCode : event.which);
      if (keycode == '13') {
        alert('You pressed a "enter" key in textbox');
      }
    });
  </script>
</body>

</html>

Upvotes: 2

Related Questions