开发者

JS: Fetch string from array that matches line in form-input

I have a form with a text-input and a submit button. In the text-input you write simple commands like /look (creating a simple game, to try out and improve my skills). In a .js-file I have an array of a few commands/strings.

My problem is: How do I match the string in the form w开发者_运维知识库ith the strings in the array. I have calculated so far that I need a for-string and a if/else-string, but I don't know how to get to that.

The html-file:

    <div id="commandField">
        <form method="POST" action="action" onSubmit="return commands(str);">
            <p class="center">Command: <input type="text" name="command" class="command" /><input type="submit" value="Execute" /></p>
        </form>
    </div>

The javascript-file:

function commands(str)
{
    var charCommand=new Array(); // regular array (add an optional integer
    charCommand[0]="/look";       // argument to control array's size)
    charCommand[1]="/use";
    charCommand[2]="/continue";
    charCommand[3]="/pickup";

    for(i=0 ; i < charCommand.length ; i++)
{
    if(str.match(charCommand[x]))
        {
            document.getElementById("commandField").innerHTML=charCommand[x];
        }
}

}


You almost have it right,
Heres what i did.

<script type="text/javascript">
        function commands(form)
    {
        var str = form.command.value;
       var charCommand=new Array(); // regular array (add an optional integer
        charCommand[0]="/look";       // argument to control array's size)
        charCommand[1]="/use";
        charCommand[2]="/continue";
        charCommand[3]="/pickup";

        for(i=0 ; i < charCommand.length ; i++)
    {
        if(str.match(charCommand[i]))
            {
                document.getElementById("commandField").innerHTML=charCommand[i];
            }
    }
    }



    </script>
    </head>
    <body>
        <div id="commandField">
            <form method="GET" action="">
                <p class="center">Command: <input type="text" name="command" class="command" />
                <input type="button" value="Execute" onClick="commands(this.form)"/></p>
            </form>
        </div>
    </body>
    </html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜