0

我对 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>
4

1 回答 1

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;
}
于 2012-06-05T22:41:19.440 回答