检测文本框是否包含某些字词

时间:2015-07-30 23:13:29

标签: javascript jquery html

我想知道如何检测文本框是否包含某些单词。例如,如果文本框中没有包含“who”,“what”,“why”,“when”或“where”某种函数的运行方式。

JavaScript的:

function command() {
    var srchVar = document.getElementById("srch");
    var srch = srchVar.value;
    var t = srch;
    if (srch == '') {
        alert('Please do not leave the field empty!');
    }
    else if (srch.indexOf('time') != -1) {
        alert('The current time according to your computer is' + ShowTime(new Date()));
    }
    else if (srch.indexOf('old are you') != -1) {
        alert("I am as old as you want me to be.");
    }
    else {
        if (confirm('I am sorry but I do not understand that command. Would you like to search Google for that command?') == true) {
            window.open('https://google.co.uk/#q=' + srch, '_blank');
        }
        else { /* Nothing */ }
    }
}

HTML:

<!DOCTYPE html>
<html>
<head>
    <script src="script.js" type="text/javascript"></script>
    <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
    <div class="ui-widget">
        <input class="search-field" id="srch" onkeypress="searchKeyPress(event);" placeholder="ask me anything" spellcheck="false">
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

按下按钮时,您将需要调用该功能。 尝试使用HTML中的内容:

<input class="info" onclick="contains();" type="button">

在你的JS中

function contains() {
    var srchVar = document.getElementById("srch");
    var srch = srchVar.value;

    if (
        (srch.indexOf('who')==-1) &&
        (srch.indexOf('what')==-1) &&
        (srch.indexOf('why')==-1) &&
        (srch.indexOf('when')==-1) &&
        (srch.indexOf('where')==-1)
    ) {
          alert("That is not a question");
    }
}

您希望以后将其与command()功能合并。

此外,info();做了什么?