遇到一个奇怪的问题,当字段为空时(当它应该为空时(,我的javascript没有正确地启动下拉项,然后在一起验证后取消其他项。当我弹出浏览器控制台时,我得到的错误是"Uncaught TypeError:无法读取未定义的属性'value'",它直接导致代码中的"if"语句结束。不确定我在哪里出了问题,我有几行相同的JS用于数字和文本输入字段,效果很好,但这一行让我很难过。
也有很多,但这是特定部分的HTML:
<div id="countryRow" class="col-xl-6 justify-content-xl-center">
<form name="countryForm" onsubmit="return validateCountry()" method="post">
<h5> </h5>
<input type="text" list="Ctry" name="selectCountry" style="width:550px;" value="">
<datalist id="Ctry">
<option value="United States">
<option value="Canada">
</datalist>
<h5>Country</h5>
</form>
</div>
这是Javascript:
function validateCountry() {
valid = true;
if (document.countryForm.countryInput.value == "") {
shipMessage.innerHTML = "This field is required";
document.getElementById("countryRow").style.backgroundColor = "#fff7f7"
valid = false;
}
return valid;
}
这只是一个小错误。您在Javascript代码中错误地命名了表单输入。并且在当前示例中没有定义shipMessage字段。在下面的代码中,我修复了这些小错误:
HTML
<div id="countryRow" class="col-xl-6 justify-content-xl-center">
<form name="countryForm" onsubmit="return validateCountry()" method="post">
<h5> </h5>
<input type="text" list="Ctry" name="selectCountry" style="width:550px;" value="">
<datalist id="Ctry">
<option value="United States">
<option value="Canada">
</datalist>
<p id="shipMessage"></p> <!-- Added this shipMessage p element to show the error -->
<h5>Country</h5>
<button type="submit">Submit</button>
</form>
</div>
Javascript:
function validateCountry() {
valid = true;
// since the name of the field is "selectCountry", so I have replaced "countryInput" with "selectCountry"
if (document.countryForm.selectCountry.value == "") {
const shipMessage = document.getElementById("shipMessage"); // defining the shipMessage variable
shipMessage.innerHTML = "This field is required";
document.getElementById("countryRow").style.backgroundColor = "#fff7f7";
valid = false;
}
return valid;
}