检查文本框中的值,使数组脚本无效

时间:2012-08-23 16:54:29

标签: javascript

我有一个脚本,我正在检查文本框中对数组的值,该数组是下拉列表中的所有值。似乎无法让它发挥作用。感谢。

<script type = "text/javascript">

    function chkName() {

        var ddlArray = new Array();
        var ddl = document.getElementById('DropDownList1');
        for (i = 0; i < ddl.options.length; i++) {
            ddlArray[i] = ddl.options[i].value;
        }



        var str = document.getElementById("TextBox1").value;
        str = str.replace(/^\s+|\s+$/g, ""); // strip leading and trailing spaces
        str = str.toLowerCase().replace(/\b[a-z]/g, function (w) {
            return w.toUpperCase()
        }); // reformat to lower-case with initial capital

        var match = false;
        for (var i = 0; i < ddlArray.length; i++) {
            if (str == ddlArray[i]) {
                match = true;
            }
        }

        if (match) {
            alert("The name " + str + " does  match our list!");
            document.getElementById("TextBox1").value = "";
            return false;
        } else {

            return true;

        }

    }
</script>

1 个答案:

答案 0 :(得分:2)

试试这个:

function chkName() {
    "use strict";
    var ddlArray = [],
        ddl = document.getElementById('DropDownList1'),
        str = document.getElementById("TextBox1").value,
        match = false;

    for (var i = 0; i < ddl.options.length; i++) {
        ddlArray[i] = ddl.options[i].value;
    }

    str = str.replace(/^\s+|\s+$/g, "");
    str = str.toLowerCase().replace(/\b[a-z]/g, function( w ) {
        return w.toUpperCase();
    });

    for (i = 0; i < ddlArray.length; i++) {
        if ( str === ddlArray[i] ) {
            alert("The name " + str + " does  match our list!");
            document.getElementById("TextBox1").value = "";
            return false;
        }
    }
    return true;
}