3

I am using an input tag of html which is supposed to work similar to input of google search.

function onKeyPressFun(event){
    var inputObj = document.getElementById("tagInput");
    var strTags = inputObj.value + String.fromCharCode(event.keyCode);
    alert("post data: strTags" + strTags);
}

I want to send the data to server to detect if any tag starting with this substring exist.
I want to add the character/string (whichever works here) from keyPress event to the existing input in the text.
As in the code above I used String.fromCharCode. When I press 'b' I found keyCode 0 and the value of String.fromCharCode(event.keyCode) was nothing; neither a blank.
Any fix for this?

3
  • "When I press 'b' I found keyCode 0" - please reproduce that on jsfiddle Commented Sep 4, 2012 at 7:49
  • 1
    Won't this be useless on keyboards that aren't your desired layout? Commented Sep 4, 2012 at 7:49
  • 1
    There is no universal mapping between keyCodes and charCodes, for obvious reasons. See @WTK's answer. Commented Sep 4, 2012 at 7:52

2 Answers 2

7

It may have something to do with support for .keyCode property across different browsers. Normalize keyCode value to get better results. One way to do it (part in parentheses is from jQuery source):

// e.g.
String.fromCharCode(event.charCode != null ? event.charCode : event.keyCode);
Sign up to request clarification or add additional context in comments.

Comments

1

You can try:

String.fromCharCode(event.which); // it works in all major browsers

Comments

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.