PDA

View Full Version : keydown and keyup issues: key codes are different in different keyboards



web.dev.2k14
06-23-2014, 04:03 AM
Hi everyone,

I am facing some serious issues regarding to validating user's input. These 2 functions work fine with Windows 7 computers with standard US keyboards (including mine), but not working properly on my client's computers (which using Windows 8, Unix and Mac OS X).



/****** Functions to check input for textboxes **********/

function check_if_input_is_numeric_only(part_of_textbox_id)
{
$('input[type="text"][id*=' + part_of_textbox_id + ']').keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}

// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}

});
}

function auto_jump_out_of_textbox_once_input_completed(part_of_current_textbox_id,max_length_for_current_textbox,part_of_id_of_next_control,is_next_control_textbox)
{
if(isNaN(max_length_for_current_textbox))
return;
if(max_length_for_current_textbox <= 0)
return;

if(typeof(is_next_control_textbox)==='undefined') is_next_control_textbox = true;
else is_next_control_textbox = false;

$('input[type="text"][id*=' + part_of_current_textbox_id + ']').keyup(function(e) {
var area_code = $(this).val();

//run this if clause only when user has filled up the textbox and the last character is a digit
if((area_code.length == max_length_for_current_textbox) && ((e.keyCode >= 96 && e.keyCode <= 105) || (e.keyCode >= 48 && e.keyCode <= 57)))
{
if(is_next_control_textbox){
$('input[type="text"][id*=' + part_of_id_of_next_control + ']').focus();
$('input[type="text"][id*=' + part_of_id_of_next_control + ']').select();
}
else
$("[id*=" + part_of_id_of_next_control + "]").focus();
}
});
}



I suspect the problem is the values for keyCode are different in different keyboards. It sometimes block my client and some of their customers (who dont use Windows 7 with standard US keyboard) from entering their data into the textboxes, even though that doesn't happen on my computer. I wonder is there anyway to make that code more generic (working on all different keyboards). Thanks.