Hey so I have two text boxes and a button. I only wanted the button enabled when the “playerName” textbox contains something and the “upperLimit” textbox contains a integer > 0.
I want the button to start disabled then dynamically change as the user is typing in the textbox, constantly checking whats in the textboxes to see if the button should be activated. Heres what I’ve tried:
JavaScript:
var playerNameValid = false;
var upperLimitValid = false;
function validatePlayerName()
{
if (document.getElementById("initialPlayerNameChoice").Value == "")
{
playerNameValid = false;
document.getElementById("startGameButton").disabled = true;
}
else
{
playerNameValid = true;
if (upperLimitValid == true)
{
document.getElementById("startGameButton").disabled = false;
}
}
}
function validateUpperLimit()
{
if (isNaN(document.getElementById("initialUpperLimitChoice").valuetextContent))
{
upperLimitValid = false;
document.getElementById("startGameButton").disabled = true;
}
else
{
upperLimitValid = true;
if (playerNameValid == true)
{
document.getElementById("startGameButton").disabled = false;
}
}
}
Markup:
<asp:Label ID="enterNameLabel" runat="server" Text="Enter your name: "></asp:Label>
<asp:TextBox ID="initialPlayerNameChoice" runat="server"></asp:TextBox>
<br /><br/>
<asp:Label ID="enterUpperLimitLabel" runat="server" Text="Enter upper limit: "></asp:Label>
<asp:TextBox ID="initialUpperLimitChoice" runat="server"></asp:TextBox>
<br /><br />
<asp:Button ID="startGameButton" enabled="false" runat="server" Text="Start Game" />
Code Behind:
initialPlayerNameChoice.Attributes.Add("onkeyup", "javascript:validatePlayerName()");
initialUpperLimitChoice.Attributes.Add("onkeyup", "javascript:validateUpperLimit()");
You’ve almost got it. There are just a few lines you need to fix in your code:
Another solution that you could implement is having just a
validate()function, and having both fields call thatonkeyup. If you changed your validation functions to return true or false, then you could eliminate the use of global variables and the logic makes more sense.And then instead for your
onkeyupcode (I don’t think you need thejavascript:part but I’m not completely sure so if it barks at you, just throw it back in):