Reputation: 191
I am trying to figure out what the difference is between onKeyPress and onKeyUp. I know that onKeyPress happens before the action was submitted and onKeyUp happens after.
My problem is what happens when the enter button is pressed?
If I use onKeyPress my code works fine and the submit button is disabled. If I use onKeyUp it will submit it, but the submit button will still be active for some reason.
Here is the code:
<script type="text/javascript">
function InformUser()
{
window.document.getElementById("loadingMessageDIV").style.display = "block";
<%=Page.GetPostBackEventReference(btnSubmit as Control)%>
document.getElementById("btnSubmit").disabled = true;
}
function validateTxt() {
var input = document.getElementById("<%=txtUserName.ClientID %>").value;
if(input.length > 0)
{
document.getElementById("btnSubmit").disabled = false;
}
else
{
document.getElementById("btnSubmit").disabled = true;
}
}
</script>
Here is the textbox that calls validateTxt()
<asp:TextBox ID="txtUserName" runat="server" Font-Size="11pt"
onkeyup="validateTxt()"></asp:TextBox>
Here is the submit button
<asp:Button ID="btnSubmit" runat="server" OnClientClick="InformUser();" OnClick="btnSubmit_Click"
Text="Login" Font-Bold="True"/>
<script type="text/javascript">
document.getElementById("btnSubmit").disabled = true;
</script>
So to recap: If I change onkeypress to onkeyup I gain the ability to captures backspaces, but when I press enter the submit button is still active.
If I change onkeyup to onkeypress then I gain the ability to press enter and have the submit button be deactivated. Downside is I can't capture backspaces.
Thanks!
Figured it out thanks to apsillers.
I had to use onkeyup with a check agaisnt the enter key
function validateTxt(event) {
var input = document.getElementById("<%=txtUserName.ClientID %>").value;
var key = event.keyCode || event.which;
if(input.length > 0 && key != 13)
{
document.getElementById("btnSubmit").disabled = false;
}
else
{
document.getElementById("btnSubmit").disabled = true;
}
}
Upvotes: 1
Views: 7991
Reputation: 115950
Fun fact: the keypress
event is not part of any standard, so browser vendors are free make it behave however they like. Coventionally, though, keypress
only fires for keys that have a printable representation. If you want to capture nonprintable key presses (arrow keys, control keys, backspace, etc.), you want keyup
(or keydown
).
Couldn't you use onkeydown
? Or use onkeyup
and check for the Enter key (e.keyCode
13)?
Other notes:
keypress
and keydown
will fire repeatedly as a key is held down, whereas keyup
only fires once.
MDN has a handy comprehensive KeyboardEvent guide with more information.
Upvotes: 3
Reputation: 4368
keypress
only works for alphabets, numbers and symbols without metakey
keyup
works for all keys on keyboard
Used jQuery in this fiddle
Upvotes: 0
Reputation: 757
Probably you would prefer perform validations onSubmit in your form.
Upvotes: 3