Why my code never alerts "be happy"?
It works for every other option, but not this one. Why so?
var i = "";
while (i != "YES"){
if(i == "NO"){
alert("You should be!");
}
else if(i == "YES") {
alert("Be happy!")
}
else{
if(i == ""){
}
else {
alert("C'mon dude... Answer simply yes or no!");
}
}
i = prompt("Are You happy?").toUpperCase();
}
Because when you enter the loop, the condition just ensure that i will never be 'Yes' when the loop starts.
Pull your i = prompt("Are You happy?").toUpperCase(); to the start of the loop.
When the user is prompted to write down "YES", you exit the while loop. Put it on top
var i = "";
while (i != "YES"){
i = prompt("Are You happy?").toUpperCase(); //*************** Put it here
if(i == "NO"){
alert("You should be!");
}
else if(i == "YES") {
alert("Be happy!")
}
else{ //Not needed (do else { alert("com...")} )
if(i == ""){
}
else {
alert("C'mon dude... Answer simply yes or no!");
}
}
}
Related
I would like the else part of the following if-statement to make that prompt pop up again. In other words, I want the prompt to come back if user writes something other than "yes" or "no".
var str = prompt("Do you want to come in?").toLowerCase();
if (srt === "yes"){
alert("cool.");
}
else if (str === "no"){
alert("goodbye.");
}
else {
var str = prompt("Do you want to come in?").toLowerCase();
}
What you need is a simple recursive function.
function showPrompt(msg) {
var str = prompt(msg).toLowerCase();
if (str === "yes") {
alert("cool.");
} else if (str === "no") {
alert("goodbye.");
} else {
showPrompt(msg);
}
}
showPrompt("Do you want to come in?");
i think you have made a typo mistake
function showPromptBox(msg) {
var str = prompt(msg) ? prompt(msg).toLowerCase() : "" ;
if (str === "yes") {
alert("cool.");
} else if (str === "no") {
alert("goodbye.");
} else {
showPromptBox(msg);
}
}
showPromptBox("Do you want to come in?");
Second way
var str = prompt("Do you want to come in?") ? prompt("Do you want to come in?").toLowerCase() : "";
if (str === "yes") {// typo mistake
alert("cool.");
}
else if (str === "no") {
alert("goodbye.");
}
else {
var str = prompt("Do you want to come in?") ? prompt("Do you want to come in?").toLowerCase() : "";
}
You can create three separate function each for handling different responsibility.
// this function will only show prompt
function showPrompt() {
return prompt("Do you want to come in?").toLowerCase();
}
// this function will be called to only show alert
function showAlert(alertText) {
alert(alertText);
}
// this function will be called to show alert and then depending on the
// value it will show alert or will call prompt
function callAlert() {
const val = showPrompt();
if (val === 'yes') {
showAlert('cool');
} else if (val === 'no') {
showAlert('goodbye')
} else {
callAlert();
}
}
callAlert();
I am writing this basic control structure for a lesson and I am getting some unexpected behavior.
var answer = prompt('what is your age');
if (answer >= 21) {
alert('good to go!');
}
else if (answer < 21) {
alert('sorry not old enough');
}
else if (answer != typeof Number) {
alert('please enter your age as a number');
}
else if (answer === null) {
alert('you did not answer!');
}
On the very last conditional, I would expect that if I left the prompt empty, it would execute the last alert. However, it just says 'not old enough'. Is it treating no input into the prompt as 0? How can fix this?
Thanks.
Prompt doesn't return null if the user hits OK, to test for emptiness, you need to check if the string is empty answer === ""
You need to move the last two checks to the top since "" < 21 is true:
var answer = prompt('what is your age');
if (answer === '') {
alert('you did not answer!');
} else if (isNaN(answer)) {
alert('please enter your age as a number');
} else if (answer >= 21) {
alert('good to go!');
} else if (answer < 21) {
alert('sorry not old enough');
}
function askQuestion(){
var Prompt = prompt("What yes or no question do you have?", "Type it here...");
var number = Math.floor((Math.random() * 8) + 1);
if(Prompt != null){
if (number == 1){
alert("Signs point yo yes.");
}else if(number == 2){
alert("Yes.");
}else if(number == 3){
alert("Reply hazy, try agian.");
}else if(number == 4){
alert("Doubtful.");
}else if(number == 5){
alert("All signs point to no.");
}else if(number == 6){
alert("Most Likely.");
}else if(number == 7){
alert("Absolutely.");
}else if(number == 8){
alert("It doesn't look good.");
}
}else{
alert("Please re-ask the Magic 8 Ball.")
}
}
<body bgColor="Black">
<center><img src="8ball.png" onClick="askQuestion()" style="cursor:pointer;"></center>
</body>
This is what I have. What I would like to know, is how to see the text typed in the prompt has a question mark at the end.
if Prompt is a string then it should just be as simple as
var lastChar = Prompt.slice(-1);
if(lastChar == '?') { .... }
if (Prompt.slice(-1) === "?") {
...
}
Old answer (substr()):
var lastChar = (Prompt.trim().substr(-1) === '?')
New answer (substring()):
var lastChar = (Prompt.trim().substring(Prompt.length - 1) === '?')
You can use the charAt() method:
var lastChar = Prompt.charAt(Prompt.length-1);
if (lastChar === "?") {
// your logic here
}
I'm trying to teach myself how to code a simple text game. I found a YouTube tutorial and am working my way through Der Kerker. A problem I have is that his final code doesn't match what he did in the videos, so I'm stuck.
Here's my problem:
When you load the game, the commands "take sword" and "help" both work as designed. However, if you put in jibberish or an unrecognized command, the game is supposed to say, "I don't understand ... "
Right now, it only clears the input box but doesn't actually run the command.
Here's my fiddle of the game:
https://jsfiddle.net/megler/hv7hqp1e/
If I remove the (check == false) portion - then the "I don't understand" part will work. However, if you type "help" - it will run the help segment AND say "I don't understand help."
The goal is for it to only say "I don't understand" if the player types in an unrecognized command.
Here's the JS:
//Check To See If True Function
var check = false;
// Been To Room Variables
var beenToCorridor = true;
//
//Inventory
var sword = false;
//
//Current Room
var currentRoom = "nCorridor";
$(document).ready(function() {
$("form").submit(function() {
var input = $("#commandLine").val();
function check() {
check = true;
}
if (input == "help") {
$("#messageHelp")
.clone()
.insertBefore("#placeholder")
.fadeIn(1000);
check();
}
if (input == "take sword" && currentRoom == "nCorridor") {
$("<p>You picked up a sword.</p>")
.hide()
.insertBefore("#placeholder")
.fadeIn(1000);
check();
}
else if (input == "take sword" && currentRoom != "nCorridor") {
$("<p>The sword is not here.</p>")
.hide()
.insertBefore("#placeholder")
.fadeIn(1000);
check();
}
else if (check == false) {
$("<p>I don't understand " + input + ".</p>")
.hide()
.insertBefore("#placeholder")
.fadeIn(1000);
}
$("#commandLine").val("");
});
});
Hope that makes sense.
I think this is what you want:
Code Replaced:
else if (input != "take sword" && input != "help") {
$("<p>I don't understand " + input + ".</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}
Snippet:
//Check To See If True Function
var check = false;
// Been To Room Variables
var beenToCorridor = true;
//
//Inventory
var sword = false;
//
//Current Room
var currentRoom = "nCorridor";
$(document).ready(function() {
$("form").submit(function() {
var input = $("#commandLine").val();
function check() {
check = true;
}
if (input == "help") {
$("#messageHelp").clone().insertBefore("#placeholder").fadeIn(1000);
check();
}
if (input == "take sword" && currentRoom == "nCorridor") {
$("<p>You picked up a sword.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
}
else if (input == "take sword" && currentRoom != "nCorridor") {
$("<p>The sword is not here.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
}
else if (input != "take sword" && input != "help") {
$("<p>I don't understand " + input + ".</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}
else
{
return false;
}
$("#commandLine").val("");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="console">
<p id="message_startGame">Welcome to my game!</p>
<p id="area_northCorridor">You are in the North Corridor. There is a sword on the ground.</p>
<p id="messageHelp" style = "display: none;">Here is a list of commands</p>
<!-- PLACEHOLDER: THIS IS WHERE EVERYTHING WILL BE INSERTED BEFORE
--->
<div id="placeholder"></div>
<form onsubmit="return false;">
<input type = "text" size ="50" autofocus="autofocus" id="commandLine">
</form>
</div>
</body>
Use different name for check variable. You should also separate last else if.
//Check To See If True Function
var _check = false;
// Been To Room Variables
var beenToCorridor = true;
//
//Inventory
var sword = false;
//
//Current Room
var currentRoom = "nCorridor";
$(document).ready(function() {
$("form").submit(function() {
var input = $("#commandLine").val();
function check() {
_check = true;
}
if (input == "help") {
$("#messageHelp")
.clone()
.insertBefore("#placeholder")
.fadeIn(1000);
check();
}
if (input == "take sword" && currentRoom == "nCorridor") {
$("<p>You picked up a sword.</p>")
.hide()
.insertBefore("#placeholder")
.fadeIn(1000);
check();
}
else if (input == "take sword" && currentRoom != "nCorridor") {
$("<p>The sword is not here.</p>")
.hide()
.insertBefore("#placeholder")
.fadeIn(1000);
check();
}
if (_check == false) {
$("<p>I don't understand " + input + ".</p>")
.hide()
.insertBefore("#placeholder")
.fadeIn(1000);
}
$("#commandLine").val("");
});
});
You should
first initialize var check = false; somewhere, otherwise the if condition never passes
add an else to your list of if ... else if ... checks.
Here's is the corrected code:
$(document).ready(function () {
$("form").submit(function () {
var input = $("#commandLine").val();
// INITIALIZE CHECK VARIABLE HERE
var check = false;
function check() {
check = true;
}
if (input == "help") {
$("#messageHelp").clone().insertBefore("#placeholder").fadeIn(1000);
check();
}
// NEEDS AN ADDITIONAL ELSE HERE TO PREVENT DOUBLE MESSAGE AFTER HELP
else if (input == "take sword" && currentRoom == "nCorridor") {
$("<p>You picked up a sword.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
} else if (input == "take sword" && currentRoom != "nCorridor") {
$("<p>The sword is not here.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
} else if (check == false) {
$("<p>I don't understand " + input + ".</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}
$("#commandLine").val("");
});
});
Reset the check variable back to false every time the form is submitted, so you s=tart from a clean slate each time it is called. Also rename your function 'check' to 'setChecked' to not cause confusion between the global variable and the local function name.
$("form").submit(function() {
check = false;
function setChecked() {
check = true;
}
if (input == "help") {
setChecked();
}
//etc...
}
It's because you redefine 'check' as a function, so it's not equal to false anymore.
The solution is to use another name for your boolean, for example 'ischeck', like this:
//Check To See If True Function
var ischeck = false;
// Been To Room Variables
var beenToCorridor = true;
//
//Inventory
var sword = false;
//
//Current Room
var currentRoom = "nCorridor";
$(document).ready(function() {
$("form").submit(function() {
var input = $("#commandLine").val();
function check() {
ischeck = true;
}
if (input == "help") {
$("#messageHelp").clone().insertBefore ("#placeholder").fadeIn(1000);
check();
}
if (input == "take sword" && currentRoom == "nCorridor") {
$("<p>You picked up a sword.</p>").hide().insertBefore ("#placeholder").fadeIn(1000);
check();
}
else if (input == "take sword" && currentRoom != "nCorridor") {
$("<p>The sword is not here.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
}
else if (ischeck == false) {
$("<p>I don't understand " + input + ".</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}
$("#commandLine").val("");
});
});
I have a html form that has 16 questions that have radio buttons to answer "Yes or No" each having a different value, after q16 the user clicks next and depending on the score the user is taken to the right page ! of 3 pages
Here is the code that I have done was working upto q9 but cannot see where I have gone wrong
function submitForm(){
var totalScore = 0;
if(document.myform.username.value.length == 0){ //make sure a name has been entered
alert('Please enter a name.');
}else if(document.myform.q1[0].checked == false && document.myform.q1[1].checked == false){// make sure q1 has been answered
alert('Please answer question 1.');
}else if(document.myform.q2[0].checked == false && document.myform.q2[1].checked == false){// make sure q2 has been answered
alert('Please answer question 2.');
}else if(document.myform.q3[0].checked == false && document.myform.q3[1].checked == false){// make sure q3 has been answered
alert('Please answer question 3.');
}else if(document.myform.q4[0].checked == false && document.myform.q4[1].checked == false){// make sure q4 has been answered
alert('Please answer question 4.');
}else if(document.myform.q5[0].checked == false && document.myform.q5[1].checked == false){// make sure q5 has been answered
alert('Please answer question 5.');
}else if(document.myform.q6[0].checked == false && document.myform.q6[1].checked == false){// make sure q6 has been answered
alert('Please answer question 6.');
}else if(document.myform.q7[0].checked == false && document.myform.q7[1].checked == false){// make sure q7 has been answered
alert('Please answer question 7.');
}else if(document.myform.q8[0].checked == false && document.myform.q8[1].checked == false){// make sure q8 has been answered
alert('Please answer question 8.');
}else if(document.myform.q9[0].checked == false && document.myform.q9[1].checked == false && document.myform.q9[2].checked == false){// make sure q9 has been answered
alert('Please answer question 9.');
}else if(document.myform.q10[0].checked == false && document.myform.q10[1].checked == false && document.myform.q10[2].checked == false){// make sure q10 has been answered
alert('Please answer question 10.');
}else if(document.myform.q11[0].checked == false && document.myform.q11[1].checked == false){// make sure q11 has been answered
alert('Please answer question 11.');
}else if(document.myform.q12[0].checked == false && document.myform.q12[1].checked == false){// make sure q12 has been answered
alert('Please answer question 12.');
}else if(document.myform.q13[0].checked == false && document.myform.q13[1].checked == false){// make sure q13 has been answered
alert('Please answer question 13.');
}else if(document.myform.q14[0].checked == false && document.myform.q14[1].checked == false){// make sure q14 has been answered
alert('Please answer question 14.');
}else if(document.myform.q15[0].checked == false && document.myform.q15[1].checked == false && document.myform.q15[2].checked == false){// make sure q15 has been answered
alert('Please answer question 15.');
}else if(document.myform.q16[0].checked == false && document.myform.q16[1].checked == false && document.myform.q16[2].checked == false){// make sure q16 has been answered
alert('Please answer question 16.');
}else{ //everything has been entered
var q1Score = 0 //work out the value of q1
if(document.myform.q1[0].checked == true){
q1Score=document.myform.q1[0].value;
}else if(document.myform.q1[1].checked == true){
q1Score=document.myform.q1[1].value;
}
var q2Score = 0 //work out the value of q2
if(document.myform.q2[0].checked == true){
q2Score=document.myform.q2[0].value;
}else if(document.myform.q2[1].checked == true){
q2Score=document.myform.q2[1].value;
}
var q3Score = 0 //work out the value of q3
if(document.myform.q3[0].checked == true){
q3Score=document.myform.q3[0].value;
}else if(document.myform.q3[1].checked == true){
q3Score=document.myform.q3[1].value;
}
var q4Score = 0 //work out the value of q4
if(document.myform.q4[0].checked == true){
q4Score=document.myform.q4[0].value;
}else if(document.myform.q4[1].checked == true){
q4Score=document.myform.q4[1].value;
}
var q5Score = 0 //work out the value of q5
if(document.myform.q5[0].checked == true){
q5Score=document.myform.q5[0].value;
}else if(document.myform.q5[1].checked == true){
q5Score=document.myform.q5[1].value;
}
var q6Score = 0 //work out the value of q6
if(document.myform.q6[0].checked == true){
q6Score=document.myform.q6[0].value;
}else if(document.myform.q6[1].checked == true){
q6Score=document.myform.q6[1].value;
}
var q7Score = 0 //work out the value of q7
if(document.myform.q7[0].checked == true){
q7Score=document.myform.q7[0].value;
}else if(document.myform.q7[1].checked == true){
q7Score=document.myform.q7[1].value;
}
var q8Score = 0 //work out the value of q8
if(document.myform.q8[0].checked == true){
q8Score=document.myform.q8[0].value;
}else if(document.myform.q8[1].checked == true){
q8Score=document.myform.q8[1].value;
}
var q9Score = 0 //work out the value of q9
if(document.myform.q9[0].checked == true){
q9Score=document.myform.q9[0].value;
}else if(document.myform.q9[1].checked == true){
q9Score=document.myform.q9[1].value;
}else if(document.myform.q9[2].checked == true){
q9Score=document.myform.q9[2].value;
}
var q10Score = 0 //work out the value of q10
if(document.myform.q10[0].checked == true){
q10Score=document.myform.q10[0].value;
}else if(document.myform.q10[1].checked == true){
q10Score=document.myform.q10[1].value;
}else if(document.myform.q10[2].checked == true){
q10Score=document.myform.q10[2].value;
}
var q11Score = 0 //work out the value of q11
if(document.myform.q11[0].checked == true){
q11Score=document.myform.q11[0].value;
}else if(document.myform.q11[1].checked == true){
q11Score=document.myform.q11[1].value;
}
var q12Score = 0 //work out the value of q12
if(document.myform.q12[0].checked == true){
q12Score=document.myform.q12[0].value;
}else if(document.myform.q12[1].checked == true){
q12Score=document.myform.q12[1].value;
}
var q13Score = 0 //work out the value of q13
if(document.myform.q13[0].checked == true){
q13Score=document.myform.q13[0].value;
}else if(document.myform.q13[1].checked == true){
q13Score=document.myform.q13[1].value;
}
var q14Score = 0 //work out the value of q14
if(document.myform.q14[0].checked == true){
q14Score=document.myform.q14[0].value;
}else if(document.myform.q14[1].checked == true){
q14Score=document.myform.q14[1].value;
}
var q15Score = 0 //work out the value of q15
if(document.myform.q15[0].checked == true){
q15Score=document.myform.q15[0].value;
}else if(document.myform.q15[1].checked == true){
q15Score=document.myform.q15[1].value;
}else if(document.myform.q15[2].checked == true){
q15Score=document.myform.q15[2].value;
}
var q16Score = 0 //work out the value of q16
if(document.myform.q16[0].checked == true){
q16Score=document.myform.q16[0].value;
}else if(document.myform.q16[1].checked == true){
q16Score=document.myform.q16[1].value;
}else if(document.myform.q16[2].checked == true){
q16Score=document.myform.q16[2].value;
}
//add the scores together
totalScore=parseInt(q1Score)+parseInt(q2Score)+parseInt(q3Score)+parseInt(q4Score)+parseInt(q5Score)+parseInt(q6Score)+parseInt(q7Score)+parseInt(q8Score)+parseInt(q9Score)+parseInt(q10Score)+parseInt(q11Score)+parseInt(q12Scorce)+parseInt(q13Score)+parseInt(q14Score)+parseInt(q15Score)+parseInt(q16Score);
if(totalScore<=15){ //if it's less than or equal to 15 go to this page...
window.location.href='greenzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
}else if (totalScore >=16 && totalScore <30){ //go to this page
window.location.href='yellowzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
}else {
window.location.href='redzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
}
}
}
To avoid this kind of repetitive code, you might want to use loops as Bergi pointed out in his comment. You could do something like this for example: (NOTE - untested!)
function submitForm() {
if(document.myform.username.value.length == 0) { //make sure a name has been entered
alert('Please enter a name.');
return;
}
var totalScore = 0;
var threeAnswerQuestions = [9, 10, 15, 16];
var numberOfQuestions = 16;
for(var i = 1; i <= numberOfQuestions; i++) {
var numerOfAnswers = threeAnswerQuestions.indexOf(i) != -1 ? 3 : 2;
var answerChecked = false;
for(var j = 0; j < numerOfAnswers; j++) {
if(document.myform['q'+i][j].checked) {
answerChecked = true;
totalScore += parseInt(document.myform['q'+i][j].value);
break;
}
}
if(!answerChecked) {
alert('Please answer question ' + i + '.');
return;
}
}
if(totalScore <= 15) { //if it's less than or equal to 15 go to this page...
window.location.href='greenzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
} else if (totalScore >= 16 && totalScore < 30) { //go to this page
window.location.href='yellowzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
} else {
window.location.href='redzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
}
}