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

Detect if a textbox does not contain certain words

本文关键字:包含某 单词 是否 文本 检测      更新时间:2023-09-26

我想知道如何检测文本框是否包含某些单词。例如,如果文本框不包含'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>

您将希望在按下按钮时调用该函数。尝试在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();做什么?