我无法使此验证正常运行。我正在验证是否已选择了一个选择框,而不是保留在我的表单中的默认选项中。
形式:
<label for="reason">How can we help?</label>
<select name="reas">
<option value="Please Select">Please Select</option>
<option value="Web Design">Web Design</option>
<option value="branding">Branding</option>
<option value="rwd">Responsive Web Design</option><span id="dropdown_error"></span>
</select>
Onclick事件:
$(document).ready(function(){
$('#contactForm').submit(function(){
return checkSelect();
});
});
功能:
function checkSelect() {
var chosen = "";
var len = document.conform.reas.length;
var i;
for (i = 0; i < len; i++){
if (document.conform.reas[i].selected){
chosen = document.conform.reas[i].value;
}
}
if (chosen == "Please Select") {
document.getElementById("dropdown_error").innerHTML = "No Option Chosen";
return false;
}
else{
document.getElementById("dropdown_error").innerHTML = "";
return true;
}
}
我也在控制台中收到此错误:
Uncaught TypeError: Cannot set property 'innerHTML' of null
我是javascript的新手,所以,我正在学习并尝试一些简单的例子,但我看不出是什么原因导致这无法验证。
任何帮助表示赞赏
答案 0 :(得分:2)
首先,您不能将错误范围置于 <select>
内。将它移到<select>
HTML之外,这将使JS错误消失。
<label for="reason">How can we help?</label>
<select name="reas">
<option value="select">Please Select</option>
<option vlaue="Web Design">Web Design</option>
<option vlaue="branding">Branding</option>
<option vlaue="rwd">Responsive Web Design</option>
</select>
<span id="dropdown_error"></span>
然后,由于您已经在使用jQuery,因此您可以将整个验证功能简化为:
function checkSelect() {
var chosen = $('select[name="reas"]').val();
if (chosen == "select") {
$("dropdown_error").text("No Option Chosen");
return false;
} else {
$("dropdown_error").text("");
return true;
}
}
答案 1 :(得分:1)
您的默认值为“选择”,并且您正在选中“请选择”。使用相同的值。
更改此
<option value="select">Please Select</option>
到
<option value="Please Select">Please Select</option>
编辑:我会使用以下代码。要修复javascript问题,请确保在关闭body标记之前放置脚本。您的脚本在解析文档之前正在执行
<label for="reason">How can we help?</label>
<select id="reas" name="reas">
<option value="">Please Select</option>
<option vlaue="Web Design">Web Design</option>
<option vlaue="branding">Branding</option>
<option vlaue="rwd">Responsive Web Design</option><span id="dropdown_error"> </span> </option>
function checkSelect() {
var chosen = document.getElementById["reas"].value;
if (chosen == "") {
document.getElementById("dropdown_error").innerHTML = "No Option Chosen";
return false;
}
else{
document.getElementById("dropdown_error").innerHTML = "";
return true;
}
}
答案 2 :(得分:1)
将您的默认选择更改为optgroup
:
<optgroup>Please Select</optgroup>
然后它将无法选择
https://developer.mozilla.org/en-US/docs/HTML/Element/optgroup