user2873816
user2873816

Reputation: 179

How to find which key was pressed

I created textfield using <input> tag.If you enter any character on textfield. I want to print that character in console.

I searched in google,everyone suggesting jQuery.I am learning Javascript so without completing Javascipt course I don't want to switch jQuery.

Upvotes: 0

Views: 110

Answers (3)

Bikas
Bikas

Reputation: 2759

It's simple implementation which doesn't require any jquery at all. You just need to call the following function on keyup

function printKey(evt) {
    var keyCode = evt.keyCode || evt.which;
    console.log(keyCode);
}

You can see it in action here http://jsbin.com/ikeVAbA/2/edit?html,js,output

Upvotes: 0

Amit
Amit

Reputation: 15387

Try this

<input type="text" onkeypress="return getCode(e)" />

function getCode(evt){
 var cc = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
 alert(String.fromCharCode(cc));
}

Upvotes: 0

Dilantha
Dilantha

Reputation: 1634

function myKeyPress(e){

            var keynum;

            if(window.event){ // IE                 
                keynum = e.keyCode;
            }else
                if(e.which){ // Netscape/Firefox/Opera                  
                    keynum = e.which;
                 }
            alert(String.fromCharCode(keynum));
        }

and your input

<input type="text" onkeypress="return myKeyPress(event)" />

You can find the list of key code here. With that you can identify which key is being pressed

Upvotes: 5

Related Questions