Reputation: 1471
I have an issue with onkeyup event of asp.net textbox. I have a requirement to allow only decimal numbers in the asp.net text box. To accomplish that i am calling a java script function from onkeyup event. The javascript function though validates the input correctly it fails in stopping the user from entering the alphabets or letters. Everything works fine with onkeychange and onkeypress events except it does not detect backspace key which drives to wrong calculation of margin percentage which relies on this textbox value .
<asp:TextBox ID="txtListPrice" runat="server" CssClass="textbox" MaxLength="50"
onkeyup= "return IsNumberKey(event);" > </asp:TextBox>
function IsNumberKey(evt) {
//obj.value = obj.value.replace(/[^0-9]/g, "");
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode <= 31 || charCode == 46 || (charCode >= 48 && charCode <= 57)) {
return CalculateMargin();
}
else {
return false;
}
}
function CalculateMargin()
{
var ListPrice = parseFloat(document.getElementById('<%=txtListPrice.ClientID%>').value);
var Cost = parseFloat(document.getElementById('<%=txtCost.ClientID%>').value);
var result = false;
if (ListPrice != NaN && Cost != NaN)
{
if ((ListPrice != "" && Cost != ""))
{
var result = Math.round(((ListPrice - Cost) / (Cost)) * 100);
document.getElementById('<%=txtMargin.ClientID%>').readOnly = false;
document.getElementById('<%=txtMargin.ClientID%>').value = result;
document.getElementById('<%=txtMargin.ClientID%>').readOnly = true;
result = true;
}
else
result = false;
}
return result;
}
Thanks
Upvotes: 1
Views: 5012
Reputation: 21887
The OnKeyUp event's keycode
property returns the character pressed in unicode
. You can use a javascript alert to see the value of the backspace key
alert(event.keyCode);
The backspace key is unicode 8. You can use that in your if statement, and then your CalculateMargin
function will run when the backspace key is pushed.
if (charCode <= 31 || charCode == 46 || (charCode >= 48 && charCode <= 57)
|| charCode == 8)
{
return CalculateMargin();
}
In your else statement, before returning false I would remove the invalid character, by searching through the string and removing any characters that are not numbers, or removing the last character in the string, which in theory should be the offending character. You can do this by using the javascript slice
function.
else
{
var txtListPrice = document.getElementById('<%=txtListPrice.ClientID%>');
var txtValue = txtListPrice.value;
txtListPrice.value = txtValue.slice(0, -1);
return false
}
Upvotes: 0