UPDATE: After debugging in IE, it seems that the "setSelectionRange" function is not supported. It's strange that it works in Visual Studio but not outside of it. The JavaScript fails at that line when running in IE, which raises the question: how can I modify the code to make it work in IE? I've explored JQuery plugins as well, but haven't found a suitable solution yet...
I have implemented some validation and auto-population logic for textboxes within a gridview using JavaScript triggered by the onkeypress event. Everything functions correctly in debug mode - character input is restricted to numbers, pressing 'y' or 'm' appends 'years' or 'months', respectively, and the cursor is positioned correctly after the number portion. This behavior is consistent in Chrome and FF. However, upon deployment of the ASPX page, IE users experience issues where the characters 'y' and 'm' are not suppressed, and the cursor placement is incorrect, resulting in strings like "9 Yearsy" or "6 Monthsm". The JavaScript code responsible is provided below. Why would this issue only arise post-deployment, and any suggestions on resolving it would be appreciated.
var timeFrame = function (evt, txtbox, max) {
if (evt.type != 'blur') {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57)) {
if (charCode == 121 || charCode == 109) {
if (charCode == 121) {
//fill with years
var entry = (txtbox.value);
var words = entry.split(' ');
if (max) {
txtbox.value = 'Maximum '.concat(words[1], ' Years');
txtbox.setSelectionRange(8 + words[1].length, 8 + words[1].length);
return false;
} else {
txtbox.value = words[0].concat(' Years');
txtbox.setSelectionRange(words[0].length, words[0].length);
return false;
}
}
if (charCode == 109) {
//fill with months
var entry = (txtbox.value);
var words = entry.split(' ');
if (max) {
txtbox.value = 'Maximum '.concat(words[1], ' Months');
txtbox.setSelectionRange(8 + words[1].length, 8 + words[1].length);
return false;
} else {
txtbox.value = words[0].concat(' Months');
txtbox.setSelectionRange(words[0].length, words[0].length);
return false;
}
}
} else {
return false;
}
}
var str = txtbox.value;
if (str != '') {
if (charCode == 46 && str.indexOf('.') !== -1) {
return false;
}
if (max) {
if (txtbox.value.indexOf('Maximum') == -1) {
txtbox.value = 'Maximum '.concat(str);
str = txtbox.value;
}
var words = str.split(' ');
if (isNaN(parseInt(words[1]))) {
txtbox.value = '';
} else {
txtbox.setSelectionRange(8 + words[1].length, 8 + words[1].length);
}
} else {
var words = str.split(' ');
if (isNaN(parseInt(words[0]))) {
txtbox.value = '';
} else {
txtbox.setSelectionRange(words[0].length, words[0].length);
}
}
}
return true;
}
}
<asp:TextBox ID="TermTextBox" runat="server" Text='<%# Bind("Term") %>' onKeyPress="return timeFrame(event, this, false);" onKeyUp="timeFrame(event, this, false);" onblur="timeFrame(event, this, false);" MaxLength="25" Width="200px" />