I was recently working on a project where we had a requirement that the first sentence typed into a textbox should be transferred to another textbox. Here is a slimmed down version of the initial implementation idea:
var questionMark = 191;
var period = 190;
var exclamationMark = 49;
$('#Summary').keyup(function (event) {
if ($('#OneLine').val().length == 0) {
if (event.keyCode == questionMark || event.keyCode == period || event.keyCode == exclamationMark)
$('#OneLine').val($('#Summary').val());
});
The idea here being to check for whether or not a period, question mark or exlamation mark was just keyed and if we hadn’t already transferred the first sentence, transfer it. Pretty straightforward and logical. A defect later popped up indicating that keys other than “.”, “?” and “!” were triggering the sentence to transfer. Somewhat puzzling at first glance, as I had always thought that a keycode would be unique for a given key (both the shift and non-shift versions). Bad assumption. After a bit of digging, it was observed that many keys map to the same keycodes. Bearing this in mind, I put together a different approach that wasn’t dependent on keyCodes since they can’t really be trusted (not only because of their lacking uniqueness, but also variance across browsers):
function extractFirstSentence(content) {
//Some arbitrarily large number that far exceeds a possible sentence length
var safeNumCap = 99999;
//Grabbing references to the first occurrences of possible sentence enders.
var indexPeriod = content.indexOf(".") > -1 ? content.indexOf(".") : safeNumCap;
var indexQuestionMark = content.indexOf("?") > -1 ? content.indexOf("?") : safeNumCap;
var indexExclamationMark = content.indexOf("!") > -1 ? content.indexOf("!") : safeNumCap;
//Determining the first-occurring index
var lowestValidIndex = Math.min(indexPeriod, indexQuestionMark, indexExclamationMark);
//Assuming our content had at least one sentence ender, returning that substring, including the sentence ender.
if (lowestValidIndex != safeNumCap)
return content.substring(0, lowestValidIndex + 1);
//Otherwise the entire content was one run-on sentence, so we didn't have a valid first sentence to extract.
else
return "";
}
The idea above was to be able to call this method with whatever frequency you desire (onBlur, onKeyUp, etc…). While this won’t solve all types of requirements that might lean on keyCodes, for this particular requirement, this worked like a charm!
Cheers,
Chris
One Response to “Javascript Event Keycodes Are Not Unique – Try And Avoid Explicit Reference”
Sorry, the comment form is closed at this time.


Very helpful post. Thanks