验证 2 个下拉列表(只有某些组合有效)
validate 2 dropdowns (only some combinations valid)
我对 JavaScript 完全陌生。
我在页面上有尺寸和颜色下拉菜单供用户订购产品,但只有某些组合可用,即粉红色是大尺寸的唯一颜色。
我想我会制作一个允许大小的数组,并根据这些大小测试用户输入。如果选择无效,那么我希望一个弹出窗口告诉用户原因。
在现实世界中,我将使用SQL和PHP来创建允许的选项数组,在下面的示例中,我硬编码了3个有效的选项进行测试。不幸的是,下面的代码没有做任何事情。
我敢肯定这是一个简单的新手错误。我真的不知道我在做什么:)
有人可以帮助我吗?
验证功能应该在用户单击表单提交时发生...
<form id="form1" name="form1" method="post" onsubmit="return validate_form()"
action="cart.php">
函数如下:
<script type="text/javascript">
function validate_form() {
var allowed = new Array();
allowed[0]="10,beige";
allowed[1]="10,black";
allowed[2]="10,pink";
var chosenColInd = document.getElementById("colID");
var chosenColText = colID.options[colID.selectedIndex].text;
var chosenSizeInd = document.getElementById("sizeID");
var chosenSizeText = sizeID.options[sizeID.selectedIndex].text;
var chosenSizeCol = chosenSizeText+","+chosenColText;
var found = "false";
for ( var i = 0; i < allowed.length; i++ ) {
if (allowed[i]=chosenSizeCol) {
found = "true";
}
}
if (found = "false") {
alert( 'The variation you have selected is currently unavailable. Please select another.' );
return false;
} else {
return true;
}
}
</script>
有
几行使用赋值运算符(即单等号=
)而不是其中一个相等运算符(即双等或三等号,JavaScript 中通常首选三等号)。例:
if (found = "false") {
乍一看似乎是问题所在 - 这是一项任务而不是比较:)使用三等号===
而不是单等号:
if(found === "false") {
此外,请考虑对代码进行以下(注释)更新,这些更新更能反映 JavaScript 代码的典型风格:
function validate_form() {
//no need to use new Array(), use array literal instead
var allowed = [
"10,beige",
"10,black",
"10,pink"
];
var chosenColInd = document.getElementById("colID");
var chosenColText = colID.options[colID.selectedIndex].text;
var chosenSizeInd = document.getElementById("sizeID");
var chosenSizeText = sizeID.options[sizeID.selectedIndex].text;
var chosenSizeCol = chosenColText+","+chosenSizeText;
var found = "false";
for ( var i = 0; i < allowed.length; i++ ) {
//use equality operator instead of assignment
if (allowed[i]===chosenSizeCol) {
found = true; //may as well use a boolean rather than string
break; //exit loop early, no need to continue if we've already found
}
}
if (!found) { //no need to do a comparison with already boolean values
alert( 'The variation you have selected is currently unavailable. Please select another.' );
}
//may as well just return found here now that we're using a boolean
return found;
}
相关文章:
- 根据id将json数组组合为一个json数组
- 接受不在列表中的值-引导组合框
- 如何有效地将游戏数据存储在URL查询字符串中
- 如何使用Node.js最有效地解析网页
- jquery代码在Mozilla中有效,但在其他浏览器上无效
- 从客户端获取修改后的对象,并将其与服务器上的原始对象组合
- 组合两个javascript函数
- Telerik rad组合框多列数据绑定
- 有效形式-始终只显示1个错误[角度]
- Javascript袖珍参考,第121页:这是怎么回事;猴子补丁”;方法应该有效
- 组合 2 个 JavaScript .scroll 函数
- 单击仅在第二次单击后有效
- 如何使用jquery组合两个数组
- 什么'是在asp.net MVC中将本地化的resources.resx文件转换为javascript文件的有效
- onChange不足以从Dojo组合框触发查询
- 为什么自我执行匿名有效
- 验证 2 个下拉列表(只有某些组合有效)
- 将 2 个数字组合起来用作对象键的有效方法是什么
- 将两个对象与多个节点组合在一起——为什么这段代码有效
- 商店没有有效的带组合减速器的减速器