/    Sign up×
Community /Pin to ProfileBookmark

Comparing Strings Seeming Not to Work

Hello,

This is a first post. I will do my best to descriptive enough.

I am a Javascript newb. An assignment I’ve been given involves making a page that works like a Magic 8 Ball (you know like, ask a yes or no question and it gives you some lame answer like “give it time” or “of course”.

First of all, had to use arrays and the math random to generate a random response. Also, have to check if the last character in the question is a question mark (?). However, the problem comes when I need to see whether or not the same question is being asked again. Meaning, I need to compare the previous input (or question) to the current input. If they match up, it is supposed to kick back with an error saying something like “Please ask a different question”.

One more thing before I post my code. The class I am taking is VERY basic and (as far as I can tell) is only teaching the concepts behind Javascript and the ways it is similar to other programming languages such as VB. That being said, they are not teaching (what i have recently found) to be proper code, so they don’t use the whole document.xxxxx, which I believe is called the DOM.. am I correct with that. Anyway, I studied forums for quite a while to teach myself DOM just to get my script working in Firefox and not just IE.
So if my code looks stupid or sloppy… that’s why. And please point out these errors to me!! I need to learrrn!

Here we go, this is the if, else if, else in the function that is called when the “Ask..” button is pressed. So my problem is when it comes to “else if (quest == prevquest) I’ve tried many different placements of declaring the variables as well (used PHP as suggested in the How to for Thread posting):

[CODE]var quest = document.getElementById(‘txtquestion’).value;
var checkquest = quest.charAt(quest.length – 1);

if (checkquest != “?”)
{
window.alert (“Please end your question with a ?”);
document.getElementById(‘txtquestion’).value = “”;
document.getElementById(‘txtquestion’).select();
return false;
}

else if (quest == prevquest){
window.alert (“Did you really think you could get away with asking the same question again? Try again.”);

document.getElementById(‘txtquestion’).value = “”;
document.getElementById(‘txtquestion’).select();
return false;

}
else{

var Select = Math.round(Math.random() * (14)) + 0;

document.getElementById(‘theAnswer’).innerHTML = “”;
document.getElementById(‘theAnswer’).innerHTML = (Ans[Select]);

document.getElementById(‘txtquestion’).select();
var prevquest = document.getElementById(‘txtquestion’).value;
}
[/CODE]

Other than it not kicking back with that alert when needed, it seems to work fine. Here is the link to where I have this posted [URL=”http://deptcis2.fvtc.edu/200011995/Web%20Development%20II/project04/Project04.html”]Magic 8 Ball[/URL]

Thank you so much for any help you can offer me!

-Keith

to post a comment
JavaScript

8 Comments(s)

Copy linkTweet thisAlerts:
@David_HarrisonSep 25.2007 — The problem is that you're using var to define your variables inside the function. Normally this is good practice, however in this case it's the source of frustration.

Using var to define a variable outside a function makes it a global variable. Using var inside a function makes it a local variable, no other code outside the function has access to it, and once the function has finished running the variable is deleted, therefore when you run the same function for a second time, it doesn't exist any more.

You can make the variable a global variable by defining it outside of the function, any code will then be able to access and change it's value, and it will persist as long as the user stays on the page.

Apart from that small issue, your code is pretty good, especially considering that you've not been at it long. A little note though, in your function you use return false a couple of times, that's not necessary in this case, since no other code depends upon the returned value of this function. Returned values can be useful in other situations though, usually when there are multiple functions that work together.
Copy linkTweet thisAlerts:
@keithfvtcauthorSep 25.2007 — Thank you very much for the response. I will try declaring the variable outside the function and then change it's value later and let you know if I get the right results.

And thanks for the return false tip!

-Keith
Copy linkTweet thisAlerts:
@keithfvtcauthorSep 25.2007 — Again thank you for the tips on variable scope and on the return false.

I've changed the code up and it all works!

I figured in case anybody else looked at this thread they might want to see before and after of the code. So here is the after. This is beginning with the declaring of the global variables:

[CODE]var Ans = new Array();
var quest;
var checkquest;
var checkYesNo;
var prevquest;

Ans[0] = "I think so";
Ans[1] = "Maybe";
Ans[2] = "Hopefully";
Ans[3] = "Nope";
Ans[4] = "Possibly";
Ans[5] = "Truthfully So";
Ans[6] = "Never in a million years";
Ans[7] = "Give me a break!";
Ans[8] = "Would ya leave me alone already?";
Ans[9] = "You're persistent, aren't you?";
Ans[10] = "Of Course";
Ans[11] = "Give it Time";
Ans[12] = "Be Patient";
Ans[13] = "Give a Script a Rest!";
Ans[14] = "Could be true...";

function GiveAnswer()
{

quest = document.getElementById('txtquestion').value;
checkquest = quest.charAt(quest.length - 1);
checkYesNo = quest.substring(0,5);

if (checkquest != "?")
{
window.alert ("Please end your question with a ?");
document.getElementById('txtquestion').value = "";
document.getElementById('txtquestion').select();

}

else if (quest == prevquest){
window.alert ("Did you really think you could get away with asking the same question? Try again.");

document.getElementById('txtquestion').value = "";
document.getElementById('txtquestion').select();


}
else if((checkYesNo == "What ") || (checkYesNo == "what ") || (checkYesNo == "Where") || (checkYesNo == "where") || (checkYesNo == "When ") || (checkYesNo == "when"))
{
window.alert ("Please ask a YES or NO question.")

document.getElementById('txtquestion').value = "";
document.getElementById('txtquestion').select();

}
else{

var Select = Math.round(Math.random() * (14)) + 0;

document.getElementById('theAnswer').innerHTML = "";
document.getElementById('theAnswer').innerHTML = (Ans[Select]);

document.getElementById('txtquestion').select();

prevquest = document.getElementById('txtquestion').value;
}

}[/CODE]


Also, you'll notice I added in a part to the else if to check if they are asking a Yes or No question and that works great too!

Thanks again!

-Keith
Copy linkTweet thisAlerts:
@David_HarrisonSep 26.2007 — To make the code slightly simpler, you could make this slight change:quest = document.getElementById('txtquestion').value.toLowerCase();It means you don't have to check for "When " and "when ", however, what if they ask a "why " or "how "?
Copy linkTweet thisAlerts:
@keithfvtcauthorSep 26.2007 — Yeah, I thought of that as I was typing out that whole else if OR thing.

Thanks!

Now, I know one way I could prevent "why" or "how" and that would be to declare another variable and extract only the first 4 characters instead of 5.. but would there be a simpler way to check them all from one variable? The problem I see right now is that I am checking 5 characters and if someone asks "how ..." it's going to pick up the first letter or so of the next word.

BTW, I added the Yes or No question part while just messing around, it isn't part of the assignment, but sometimes when I get an idea, I just Have to try it to see if it works. ?

Thanks again. Much appreciated.
Copy linkTweet thisAlerts:
@David_HarrisonSep 26.2007 — Well, you could look into something called regular expressions. Normally I don't like to use them because they can be pretty hard to read, however there's no denying that they can be very powerful.

Basically, when you define a regular expression, it's a pattern that you can then use on a string, to see if it matches the pattern and if so you can even extract bits of the string that would be difficult to find with another method. The problem with regular expressions is that sometimes they can look like someone was headbutting the keyboard as they were typing it.

Take a [url=http://www.webreference.com/js/column5/]read through this[/url], it should be enough to get you started so that you can define a few basic patterns to help with this script.
Copy linkTweet thisAlerts:
@keithfvtcauthorSep 26.2007 — Very cool. I've started reading at that link. I love learning this stuff!
Copy linkTweet thisAlerts:
@Tweak4Sep 26.2007 — Don't let regular expressions scare you. It takes a little work to completely understand them, but after that, they're not difficult, and they make for extremely powerful tools with similar implementations in most modern languages.

For work, we use them extensively in both JS and C# for validating user input.
×

Success!

Help @keithfvtc spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...