Gamer Vang
Gamer Vang

Reputation: 32

onkeypress would not work for a if the same

I wanted to make if you press s it would make the id alert you click s, but it was no working See it for your self

javascript

function myFunction(event) {
  var x = event.which || event.keyCode;
  if (x == 155){
    alert("You press s button");
  }
}

html

    <body onkeypress="myFunction(event)">
       <input type="text" size="40">
       <p id="demo"></p>
    </body>https://jsfiddle.net/hsoeutxr/

but, it only work

function myFunction(event) {
  var x = event.which || event.keyCode;
  alert("You press s button");
}

So I would think it would be the if statement but I didn't see any problems

Upvotes: 0

Views: 41

Answers (2)

Tanvir Rahman
Tanvir Rahman

Reputation: 709

Compare it with keycode 115. In your myFunction the keycode will be -

  function myFunction(event) {
    var x = event.which || event.keyCode;
    if (x == 115) {
     alert("Hello");
    }
  }

Upvotes: 1

Jamar P
Jamar P

Reputation: 11

I would use typeof to check and see if x is a number because it might be a string to start with.

Upvotes: 0

Related Questions