我正在开发一个代码,其中服务从数据库进入<li></li>
标记。
当前只有少数服务处于活动状态,如果用户选择服务且该服务处于活动状态,则继续,如果没有,则应显示警告消息。
我不知道为什么这个function validation()
没有被执行。
任何帮助将不胜感激
下面是我正在处理的代码:
<script language="javascript">
function validation() {
var category = document.getElementById("category").value;
category = category.trim();
if (category == "") {
alert("Please Select Category.");
return;
} else {
var limiter = ["Electrician", "Photographer", "Printing Press", "Website Designer", "Web developer", "DJ Music", "Coaching Classes", "Civil Contractor", "Computer Hardware Services"];
var limiter_count = limiter.length;
for (var i = 0; i < limiter_count; i++) {
if (category == limiter[i]) {
document.getElementById("form1").action = "categoryforms.php";
document.getElementById("form1").submit();
//loop should be terminated
} else {
var alrt = "We will soon be launching our service in " + category + ", kindly stay tuned...";
alert(alrt);
//loop should be terminated here also
}
}
}
}
</script>
表单格式为:
<form action="" method="post" name="form1" id="form1" >
<input type="text" name="category" id="category" value="<?php echo $category; ?>" />
<ul id="categorymenu" class="mcdropdown_menu">
<?php
$sql = "SELECT * FROM category";
$sql_result = mysql_query ($sql);
while ($row = mysql_fetch_assoc($sql_result)){
?>
<li rel="<?php echo $row["category"]; ?>" value="<?php echo $row["category"]; ?>" ><?php echo $row["category"]; ?> </li>
<?php
}
?>
</ul>
<input id="button" type="button" value="Send " class="serch" onClick="javascript:validation()">
</form>
答案 0 :(得分:1)
您不需要循环,使用Array.prototype.indexOf()
检查元素是否存在于数组中。
indexOf()
方法返回可在数组中找到给定元素的第一个索引,如果不存在,则返回-1
。
脚本
function validation() {
var category = document.getElementById("category").value;
category = category.trim();
if (category == "") {
alert("Please Select Category.");
return;
}
var limiter = ["Electrician", "Photographer", "Printing Press", "Website Designer", "Web developer", "DJ Music", "Coaching Classes", "Civil Contractor", "Computer Hardware Services"];
var index = limiter.indexOf(category);
if (index > -1) {
document.getElementById("form1").action = "categoryforms.php";
document.getElementById("form1").submit();
//loop should be terminated
} else {
var alrt = "We will soon be launching our service in " + category + ", kindly stay tuned...";
alert(alrt);
//loop should be terminated here also
}
}