0

I have a script that I am checking values from textbox against an array, the array are all values from a drop down list. Cant seem to get it to work. Thanks.

<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>
7
  • 2
    Where did "v" come from? Commented Aug 23, 2012 at 16:57
  • And you can leave the loop like this match = true; break; Commented Aug 23, 2012 at 17:00
  • Nitpick Doing document.getElementById("TextBox1") over and over again in the same function is bad. Store it in a variable and reference it. Also most modern day browsers support indexOf on arrays. Commented Aug 23, 2012 at 17:02
  • try to debug your code by yourself. console.log([str, ddlArray[i]]); Commented Aug 23, 2012 at 17:04
  • Instead of "new Array()", use "[ ]". And inside of your if statement to check for a match, you can use "break;" after the "match = true;" line. (these won't fix anything, just improve whatever) Commented Aug 23, 2012 at 17:08

1 Answer 1

2

Try this:

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.