0

I want convert following working jQuery code into JavaScript

$(document).ready(function(){
    $("#txt1").keydown(function(event){
        var keyPress=String.fromCharCode(event.keyCode);
        var Keycode=event.keyCode;
        alert("KeyPress : "+keyPress)
        alert("KeyCode : "+Keycode)   
    })
})

and I am trying this to replace this code with JavaScript

document.getElementById("txt1").onkeydown=function(event){
    var keyPress=String.fromCharCode(event.keyCode);
    var Keycode=event.keyCode;
    alert("KeyPress : "+keyPress)
    alert("KeyCode : "+Keycode) 
}

and this above code not working.

5
  • document.getElementById("txt1").addEventListener('keydown', function(event) { ... }); Commented Nov 5, 2017 at 13:38
  • which part doesn't work? Commented Nov 5, 2017 at 13:39
  • @baao Are you going to post this as an answer or should I ? Commented Nov 5, 2017 at 13:39
  • 1
    To be clear, jQuery is JavaScript. jQuery is a JavaScript library. Commented Nov 5, 2017 at 13:39
  • feel free to post it @KobyDouek Commented Nov 5, 2017 at 13:40

1 Answer 1

1

Try this:

window.onload = function() {
  document.getElementById("txt1").addEventListener("keydown", function(e) {
    keyPress = String.fromCharCode(e.keyCode);
    keyCode = e.keyCode;    
    alert("KeyPress : " + keyPress)
    alert("KeyCode : " + keyCode)  
  }, false);
}
Sign up to request clarification or add additional context in comments.

1 Comment

What does that do? How does it answer the question? Don't just blurt out code. Explain yourself! stackoverflow.com/help/how-to-answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.