backspace and delete characters not working when a textbox is validated for duplicate source code
I have the following javascript function to validate the usercode value entered in the textbox,i am not allowing them to allow duplicate characters like AABC , BBCF.... etc, but the problem is after entering some characters its not allowing to delete the entered characters.
function ValidateUserCode(txtid,e)
{
var validateText = document.getElementById(txtid).value;
var userText = validateText.toUpperCase();
if (window.event)
{
e = window.event;
}
if (e.keyCode) {
code = e.ke开发者_如何学编程yCode;
}
else if (e.which) {
code = e.which;
characterCode = String.fromCharCode(e.which);
characterCode = characterCode.toUpperCase();
}
if (userText.indexOf(characterCode) < 0)
{
return true;
}
else {
return false;
}
}
This my code on aspx page
<asp:label Text=" Code" runat="server" ID="Label"></asp:label>
</div>
<asp:TextBox ID="CodeTextBox" runat="server" Size="6" MaxLength="4" Style="text-transform: uppercase;" ></asp:TextBox><br />
This my codebehind where i make javascript call
protected void Page_Load(object sender, EventArgs e)
{
IntializeEventHandlers();
}
private void IntializeEventHandlers()
{
this.CodeTextBox.Attributes.Add("onkeypress", string.Format("javascript:return ValidateUserCode('{0}',event);",this.CodeTextBox.ClientID));
}
Here is a working set of code based on what you want to do that will work in multiple browsers, and properly handles the delete/backspace/arrow keys:
function ValidateUserCode(txtid, e) {
var validateText = document.getElementById(txtid).value;
var userText = validateText.toUpperCase();
var code = e.which;
if (!code && ((e.charCode || e.charCode === 0) ? e.charCode : e.keyCode)) {
code = e.charCode || e.keyCode;
}
var characterCode = String.fromCharCode(code).toUpperCase();
return (userText.indexOf(characterCode) < 0);
}
Update
Here's the html I used to test this:
<input type="text" id="mytext" onkeypress="return ValidateUserCode('mytext',event);" />
Make sure that the rendered html from your ASP code looks similar to this, and that the id values match.
精彩评论