How to use an if statement to disable a button?

Associate
Joined
26 Aug 2014
Posts
2
Hi I have the following code...


Code:
<!doctype html>
<html>
<head>
<title>Loops</title>
</head>

<body>
<form id = "frmOne">
<table border="1" >
	<p>Items Remaining: <a id="clicks">5</a></p>
	<tr>
	<th> Number One:</th>
	<th> Number Two:</th>
	</tr>

	<tr>
	<td> <Input Type="Text" Name="txtFirstNumber" Size="5" value=""> </td>
	<td> <Input Type="Text" Name="txtSecondNumber" Size="5" value=""> </td>
	</tr>

	<tr>
	<td colspan="2"> Totals: <textarea Name="totals" style="width: 400px; height: 300px;"></textarea></td>
	</tr>

	<tr>
	<td colspan="2"> <Input Type="Button" Name="b1" Value="Add Numbers" onClick = calculate()> </td>
	</tr>
</table>
</form>

<script>
var Totals = [ ];
var clicks = 5;

function calculate() {
        var form = document.getElementById("frmOne"); 
	var A = form.txtFirstNumber.value;
	var B = form.txtSecondNumber.value;

	Totals.push( A + " + " + B + " = " + (1*A+1*B) );
        
        form.totals.value = Totals.join("\n");

	form.txtFirstNumber.value = form.txtSecondNumber.value = "";

	clicks -= 1;
        document.getElementById("clicks").innerHTML = clicks;

}
</script>
</body>
</html>

I want to add in an if statement that checks to see if the number of items remaining is 0. If it is 0, I want it to say finished and the button be disabled / disappear.

Can anyone help?

TIA
 
Associate
Joined
3 Jan 2010
Posts
175
Location
Birmingham, England
Like this?

Code:
<!doctype html>
<html>
	<head>
		<title>Loops</title>
	</head>
	<body>
		<form id = "frmOne">
			<table border="1" >
				<p>Items Remaining: <a id="clicks">5</a></p>
				<tr>
					<th>Number One:</th>
					<th>Number Two:</th>
				</tr>

				<tr>
					<td><input Type="Text" Name="txtFirstNumber" Size="5" value=""> </td>
					<td><input Type="Text" Name="txtSecondNumber" Size="5" value=""> </td>
				</tr>

				<tr>
					<td colspan="2">Totals: <textarea Name="totals" style="width: 400px; height: 300px;"></textarea></td>
				</tr>

				<tr>
					<td colspan="2"><input Type="Button" Name="b1" id="b1" Value="Add Numbers" onClick = "calculate()"> </td>
				</tr>
			</table>
		</form>

		<script>
			var Totals = [ ];
			var clicks = 5;
			function calculate() {
				var form = document.getElementById("frmOne"); 
				var A = form.txtFirstNumber.value;
				var B = form.txtSecondNumber.value;

				Totals.push( A + " + " + B + " = " + (1*A+1*B) );

				form.totals.value = Totals.join("\n");

				form.txtFirstNumber.value = form.txtSecondNumber.value = "";

				clicks -= 1;
				document.getElementById("clicks").innerHTML = clicks;

				if (clicks == 0) {
					alert("Finished!");
					document.getElementById("b1").disabled = true;
				};
			}
		</script>
	</body>
</html>
 
Last edited:
Back
Top Bottom