如何使用javascript和php禁用数字输入类型

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (53)

我正在开发一个包含一个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>

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

提问于
用户回答回答于

您应该将其与其他输入的总和进行比较,而不是递减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事件

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

扫码关注云+社区

领取腾讯云代金券