var input = document.querySelector("input");
var button = document.querySelector("button");
var inventory = ["jacket","pants","map"];
var actionsIKnow = ["north","east","west","south"];
var messages = ["A group of dangerous minions. Turn back, you do not have a sword",
"You have gone too deep into the forest. Want to go further?",
"A giant ruby crystal",
"A silent lake; you see your reflection in the water",
"Clear patch of land",
"A sleeping dragon. Bettwe not wake it up",
"A solitary cottage. Faint music can be heard from the inside",
"Looks like this path leads to the cottage of the flute maker",
"A lot of tombstones, looks like an old graveyard"
];
var userInput;
var startingPos = 4;
button.addEventListener("click",takeMeThere,false);
function takeMeThere(){
userInput = input.value;
userInput = userInput.toLowerCase();
if(userInput!=null){
validateInput();
}
}
function validateInput(){
for(var i=0;i<actionsIKnow.length;i++){
if(userInput.indexOf(actionsIKnow[i]!=-1)){
move(actionsIKnow[i]);
}
}
}
function move(where){
console.log(where);
}
I am making a text based exploring game where the user can select where to go. Where the user wants to go depends on what was entered in the textfield. This data is then passed to move(where) where I console.log(where). Instead of printing north, east, etc it prints the whole of actionsIKnow array. Why ?
if(userInput!=null){will never be false..valueattribute returns a string, and the string method.toLowerCase()also returns a string. To test that the field is not empty compare to an empty string:if (userInput!=""){. You may also like to first trim any white space:userInput = userInput.replace(/\s/g,"");, in case the user enters nothing but spaces...