验证 2 个下拉列表(只有某些组合有效)

validate 2 dropdowns (only some combinations valid)

本文关键字:组合 有效 下拉列表 验证      更新时间:2023-09-26

我对 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;
}