我是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>
答案 0 :(得分:0)
您可以使用赋值运算符(即单个等于=
)代替其中一个等于运算符(两个或三个等于,在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;
}