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?

veer7
  • 20,074
  • 9
  • 46
  • 74

2 Answers2

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);
WTK
  • 16,583
  • 6
  • 35
  • 45
1

You can try:

String.fromCharCode(event.which); // it works in all major browsers
micnic
  • 10,915
  • 5
  • 44
  • 55