如何使用JavaScript和PHP禁用数字输入类型

时间:2018-12-12 19:00:13

标签: javascript php

我正在处理一个包含php页面的小项目,该页面将要求用户输入测试的多个问题,并在编写了例如10的数字后,他将为每种类型的问题分配一个问题的数量。考试(加法,减法,乘法,除法)直到问题数量结束为止,例如,在选择了10个总问题之后,他可以再选择5个乘法(3个乘法和2个除法),但是由于10个总问题已经完成,他不能再分配问题。并且他在html中以数字输入类型分配这些数字,因此我想获取第一个输入类型,即问题总数,然后每当他增加任何一种考试类型(加法..)和当它达到0时,它将禁用输入类型,这是我到目前为止所做的:

var numInput = document.getElementById('numInput');
var Input1 = document.getElementById('Input1');
var Input2 = document.getElementById('Input2');
var Input3 = document.getElementById('Input3');
var Input4 = document.getElementById('Input4');

Input1.disabled = true;
Input2.disabled = true;
Input3.disabled = true;
Input4.disabled = true;

var Checker = setInterval(function Checker() {
var numValue = numInput.value;
//thats what I tried to do to solve my problem but it didn't work properly because it must decrement only 1 but the condition will still be true so it will decrement for ever or at least that is what I think.
if (Input1.value > 0) {
	numValue = numValue - 1;
}
//and this part is working fine.
if (numValue > 0) {
	Input1.disabled = false;
	Input2.disabled = false;
	Input3.disabled = false;
	Input4.disabled = false;
} else if (numValue <= 0) {
	Input1.disabled = true;
	Input2.disabled = true;
	Input3.disabled = true;
	Input4.disabled = true;
}
}, 100);
<form method="GET" action="">
	<h2>How many questions do you want to answer?</h2>
	<input id="numInput" type="number" name="Text" value="0" min="0"><br>	
	<h2>Addition: </h2>&nbsp<input id="Input1" type="number" name="Text" value="0" min="0"><br>
	<h2>Subtraction: </h2>&nbsp<input id="Input2" type="number" name="Text" value="0" min="0"><br>
	<h2>Multiplication: </h2>&nbsp<input id="Input3" type="number" name="Text" value="0" min="0"><br>
	<h2>Division: </h2>&nbsp<input id="Input4" type="number" name="Text" value="0" min="0">
</form>

我对如何解决这个问题一无所知,请帮助我。

1 个答案:

答案 0 :(得分:1)

您不应将numValue递减,而应将其与其他输入的总和进行比较

function Checker() {
var sum=parseInt(Input1.value)+parseInt(Input2.value)+parseInt(Input3.value)+parseInt(Input4.value);
var numValue = numInput.value;
if (numValue > sum) 
{
    Input1.disabled = false;
    Input2.disabled = false;
    Input3.disabled = false;
    Input4.disabled = false;
} else  
{
    Input1.disabled = true;
    Input2.disabled = true;
    Input3.disabled = true;
    Input4.disabled = true;
    }
}

此外,最好使用setInterval,使用onchange event

numInput.addEventListener("change", Checker);
Input1.addEventListener("change", Checker);
Input2.addEventListener("change", Checker);
Input3.addEventListener("change", Checker);
Input4.addEventListener("change", Checker);