我希望用户输入正确的总和并进行验证。验证完成后,它将带来一个文本文件。
<fieldset>
<legend style="font-size: 30px; color: red;">Verification table</legend>
<form>
<label>The sum of 7 + 2 : </label> <input type="number" id="inputNumberBox" />
<button type="submit" id="submitBtn" onsubmit="myFunction()">Hit me Baby!!
</button>
</form>
</fieldset>
function myFunction() {
var inputValue = document.getElementById("inputNumberBox").value;
function checkValidation() {
if (inputValue == 9) {
var client = new XMLHttpRequest();
client.open('GET', '/testText.txt');
client.onreadystatechange = function() {
alert(client.responseText);
}
client.send();
} else {
window.alert("Try again");
}
}
clickButton.addEventListener("click", checkValidation, false);
}
最佳答案
你有很多不必要的函数甚至没有被调用,你可以删除你的 checkValidation()
和 readText()
并且它们里面的代码可以呈现为它们是,请参阅下面我的意思 -
function myFunction() {
var inputValue = document.getElementById("inputNumberBox").value;
var clickButton = document.getElementById("submitBtn");
if (inputValue == 9) {
// enter your code for getting the text file
} else {
window.alert("Try again");
}
}
同样在你的html
中,你已经定义了事件监听器,onsubmit
myFunction()
被调用,所以你的最后一行JS代码又不需要了。
请参阅工作示例 here .
关于javascript - 如何使用 Javascript 添加事件监听器来验证用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32520356/