我在根据验证中的 if/else 语句显示字符串时遇到问题。
如果你看下面的代码,如果满足 if
语句,那么它会显示消息,这很好,但是当我确定 if
语句时满足并故意使 else if
语句失败,而不是显示消息,而是仅显示空白。为什么在下面的 JavaScript 验证中满足 else if
语句时不显示消息:
function editvalidation() {
var isDataValid = true;
var currentAssesO = document.getElementById("currentAssessment");
var noStudentsO = document.getElementById("addtextarea");
var studentAssesMsgO = document.getElementById("studentAlert");
studentAssesMsgO.innerHTML = "";
if (currentAssesO.value == ""){
$('#targetdiv').hide();
studentAssesMsgO.innerHTML = "Please Select an Assessment to edit from the Assessment Drop Down Menu";
isDataValid = false;
}else if (noStudentsO.value == ""){
$('#targetdiv').hide();
studentAssesMsgO.innerHTML = "You have not Selected any Students you wish to Add into Assessment";
isDataValid = false;
}
else{
studentAssesMsgO.innerHTML = "";
}
return isDataValid;
}
更新:
HTML:
选择框(选项附加到此框中):
<select multiple="multiple" name="addtextarea" id="studentadd" size="10">
</select>
下拉菜单:
<select name="session" id="sessionsDrop">
<option value="">Please Select</option>
<option value='20'>EWYGC - 10-01-2013 - 09:00</option>
<option value='22'>WDFRK - 11-01-2013 - 10:05</option>
<option value='23'>XJJVS - 12-01-2013 - 10:00</option>
</select> </p>
警报消息:
<div id='studentAlert'></div>
验证要求:
如果下拉菜单为空,则显示需要从警报消息 div 中的下拉菜单中选择评估的消息。
如果下拉菜单不为空,则检查选择框是否包含任何选项,如果选择框不包含任何选项,则替换 div 警报消息,说明尚未选择任何学生添加到评估中
如果下拉菜单不为空且选择框不为空(或者换句话说包含选项),则 div 警报消息只是一个空字符串
""
最佳答案
这样改写你的 JavaScript:
function editvalidation() {
var isDataValid = true;
var currentAssesO = document.getElementById("currentAssessment");
var noStudentsO = document.getElementById("addtextarea");
var studentAssesMsgO = document.getElementById("studentAlert");
var errorMsg = "";
studentAssesMsgO.innerHTML = "";
if (currentAssesO.value == "" || noStudentsO.value == "") {
$('#targetdiv').hide();
isDataValid = false;
if (currentAssesO.value == "") {
errorMsg += "Please Select an Assessment to edit from the Assessment Drop Down Menu";
}
if (noStudentsO.value == "") {
errorMsg += "You have not Selected any Students you wish to Add into Assessment";
}
studentAssesMsgO.innerHTML = errorMsg; // Plus whatever styling for messages.
}
return isDataValid;
}
更新答案
请将 jQuery 放入 <head>
中部分。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
更新您的脚本:
function editvalidation()
{
if ($("#sessionsDrop").val()=="")
$("#studentAlert").html("Assessment needs to be filled.");
if ($("#sessionsDrop").val()!="" && $("#studentadd").children().length==0)
$("#studentAlert").html("No students have been selected to add to assessment.");
if ($("#sessionsDrop").val()!="" && $("#studentadd").children().length!=0)
return true;
return false;
}
关于javascript - else if javascript 中的语句无法显示验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14269995/