Skip to content Skip to sidebar Skip to footer

How To Look For A Word In Textbox In JavaScript

I am making a website simular to the app Google Now and I was wondering how to make JavaScript look for a certain word in a textbox. So for example if someone was to type 'Show me

Solution 1:

You can check if string contains substring. Use indexOf function, it returns position of given string in its parent string. Try this:

if (txtVal == '') {
    alert('Please fill in the text box. For a list of commands type "Help" into the text box.');
} else if (txtVal.indexOf("start") != -1) {
    alert('Hello. What would you like me to do?');
} else if (txtVal.indexOf("weather") != -1) {
    window.location = "https://www.google.com/#q=weather";
}
// and so on.

Function returns -1, if the value start is not found.

And. If you have lots and lots of those functions, you should put all the function words to array, and then avoid that too large if/else system. Then you should check that array, if corresponding function exists. I made function to help your project:

function returnWord(value, array) {
    if (!(value in array)) {
        return array[value]();
    }
    else {
        alert('returnWord() error: No needle found in haystack');
    }
}

Call it like this:

var words = {
             start: function() { alert('Hello. What would you like me to do?'); },
             weather: function() { window.location = "https://www.google.com/#q=weather"; },
             time: function() { alert('The current time according to your computer is' + formatTime(new Date())); },
             /* all the functions here */
            };

returnWord(txtVal, words);

Solution 2:

Simple you can go like this

var str = document.getElementById("textbox1");
var n = str.indexOf("welcome");

if(n != -1){
 //Do what you want
}else{
 //Get Out
}

Solution 3:

Use can also use search() method:

...
if (txtVal.search("start") != -1) {
   alert('Hello. What would you like me to do?');
}
...

Check here: http://www.w3schools.com/jsref/jsref_search.asp


Post a Comment for "How To Look For A Word In Textbox In JavaScript"