How to come back to the start prompt after else? - javascript

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();

Related

how to reduce if statements in javascript?

I'm writing code in vanilla JavaScript but I don't want to write a thousand different if statements.
I already tried searching up how to reduce if statements in JavaScript, but I didn't find anything helpful.
Here is some example code:
if (a == "text" && b == "othertext") {
console.log("message");
} else if (a == "text2" && b == "othertext2") {
console.log("other message");
} else if (a == "text3" && b == "othertext3") {
console.log("other other message");
} else if (a == "text4" && b == "othertext4") {
console.log("other other other message");
} else if (a == "text5" && b == "othertext5") {
console.log("other other other other message");
} else if (a == "text6" && b == "othertext6") {
// .. and so on.
}
If anyone can help me, it would be appreciated
You can use a data-driven approach by using the strings as keys in an object.
const messages = {
"text|othertext": "message",
"text1|othertext1": "message1",
"text2|othertext2": "message2"
};
function showMessage(a, b) {
let key = `${a}|${b}`;
if (messages.hasOwnProperty(key)) {
console.log(messages[key]);
} else {
console.log("Invalid a and b");
}
}
showMessage("text", "othertext");
You could use ternary operators I suppose.
let msg = '';
msg = a === 'text' && b === 'othertext' : msg;
msg = a === 'text2' && b === 'othertext2' : msg;
// etc.
Ultimately its not gonna get much prettier but that might be a little bit simpler to type.

Error: text.replace is not a function in angularjs filter, how to fix this?

in the angular i trying to use filter in angular to replace some string with another word that it can find, i already try many example, i think my code is just missing something, but i can't figure it out. Here is my code :
here is my app.js
app.filter('filterStatus', function () {
return function (text) {
if(text == 1){
return str = text.replace(/1/g, "Waiting");
} else if (text == 2) {
return str = text.replace(/2/g, "On Process");
} else if (text == 3) {
return str = text.replace(/3/g, "On The Way");
} else if (text == 4) {
return str = text.replace(/4/g, "Delivered");
} else if (text == 5) {
return str = text.replace(/5/g, "Expired");
}
};
});
i going to replace "1" with "Waiting" word, here is my html page
<tr ng-repeat-start="siheaders in singleID.siheader">
<td>{{siheaders.status | filterStatus}}</td>
</tr>
but it give me these "Error: text.replace is not a function" error when i use firebug to debug it, what am i missed here?
There's really no need to do any string replacement.
app.filter('filterStatus', function () {
return function (text) {
if(text == 1){
return "Waiting";
} else if (text == 2) {
return "On Process";
} else if (text == 3) {
return "On The Way";
} else if (text == 4) {
return "Delivered";
} else if (text == 5) {
return "Expired";
}
};
}

Need help correcting a function in text game

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("");
});
});

Javascript - while loop doesn't show success option

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!");
}
}
}

jConfirm message cannot work properly

The confirmation popup always return true. Please advice the correction needed.
$('#btnDelete').click(function () {
var check = false;
var aCheckbox = document.getElementsByTagName('input');
for (var i = 0; i < aCheckbox.length; i++) {
if (aCheckbox[i].type === 'checkbox' && aCheckbox[i].checked) {
check = true;
}
}
if (check === true) {
return jConfirm('Do u really want to delete?', 'Confirmation');
} else {
jAlert("Please select serial number", 'Alert');
return false;
}
});
Hope this help :
if (check === true) {
var answer = confirm('Do u really want to delete?', 'Confirmation');
if(answer)
return true;
else
return false;
}
else {
jAlert("Please select serial number", 'Alert');
return false;
}
Yes it creates problem you need to use third parameter as callback function of jconfirm like,
if (check === true) {
jConfirm('Do u really want to delete?', 'Confirmation', function(r) {
jAlert('Confirmed: ' + r, 'Confirmation Results');
});
return false;
} else {
.....
Also remove extra closing }); from your code, see last two lines.

Categories