Case not working on second input? - javascript

I am trying to create a text based game that takes information inputted in the browser and translates it into an action and runs it. I am able to get it to work for the first answer but after it displays the outcome of the first answer it doesn't seem to load the second. Also once you submit anything all the cases show up and are appended to the screen without any input. Any idea how to fix this issue or make sure the case keeps repeating?
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Lord of the Deahsticks</title>
<link href="css/text-game.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="info">
<h1 class="title">Lord of the Deathsticks</h1>
</div>
<div class="gameboard">
<div class="event">
<p>Hello this is the game!</p>
</div>
<div class="event">
<p>You are awoken by a sound...You need to get up already, you're going to be late for you shift at the slave factory!</p>
</div>
</div>
<form>
<input type="text" id="action" name="what to do">
<input type="submit" name="button">
</form>
<script src="js/controllers/controller.js"></script>
<script src="js/model/characters.js"></script>
<script src="js/JQuery/jquery-3.1.0.js"></script>
<script src="js/JQuery/text-game-JQuery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</body>
</html>
Main js/jquery
var template = function(action){
return '<div class="event"><p>'+ action +'</p></div>'
};
var display = function(input){
if(input !== "") {
var html = template(input);
$(html).appendTo('.gameboard');
} else {
alert("You need to imput an appropriate answer");
}
$('#action').val("");
$('#mydiv').scrollTop(($('#mydiv').height()*2));
};
var main = function(){
$('form').submit(function(){
event.preventDefault();
var action = $('#action').val();
var input = action.toLowerCase();
display(action);
interact(input);
return false;
});
};
$(document).ready(main);
Controller:
var where = "intro";
var wait = function(){
};
var interact = function(input) {
switch(where) {
case "intro":
if (input === "stay in bed") {
display("you sleep for 2 more hours");
where = "police";
} else if (input === "wake up") {
display("You wake up and head to the slave factory");
where = "on route";
} else {
display("You need to submit a valid response");
}
break;
case "police":
display("You are awaken by three slave police standing at your bed!");
wait();
display("Our records show this is you third offence citizen #000986642, you will now be sent for disciplinary reconditioning. Prepare to be detained.")
wait();
display("what will you do? -Go with them? -Fight them? -Try to Escape");
if (input === "go with them") {
display("You are escorted to the deathcamp");
where = "deathcamp1";
} else if (input === "fight them") {
display("You jump out of bed and prepare for a fistfight");
where = "fistfight";
} else if (input === "try to escape") {
display("you attempt to jump through your window");
where = "window1";
} else {
display("You need to submit a valid response");
}
break;
}
};

You have the right idea and your code works. It's just you might need to rethink some of your logic and maybe add some more error handling (if needed).
I've updated your code:
var interact = function(input) {
switch(where) {
case "intro":
if (input === "stay in bed") {
setTimeout( function() { display("you sleep for 2 more hours"); }, 1000);
setTimeout( function() { display("You are awaken by three slave police standing at your bed!"); }, 3000);
setTimeout( function() { display("Our records show this is you third offence citizen #000986642, you will now be sent for disciplinary reconditioning. Prepare to be detained."); }, 5000);
setTimeout( function() { display("what will you do? -Go with them? -Fight them? -Try to Escape"); }, 7000);
where = "police";
} else if (input === "wake up") {
display("You wake up and head to the slave factory");
where = "on route";
} else {
display("You need to submit a valid response" + where);
}
break;
case "police":
if (input === "go with them") {
display("You are escorted to the deathcamp");
where = "deathcamp1";
} else if (input === "fight them") {
display("You jump out of bed and prepare for a fistfight");
where = "fistfight";
} else if (input === "try to escape") {
display("you attempt to jump through your window");
where = "window1";
} else {
display("You need to submit a valid response");
}
break;
}
};
You want to have the output in the stay in bed command, that way it will only happen once. Then you use the next case to present the next output or error message if necessary. Good luck on your story!
Also you'll find .setTimeout(function, milliseconds) useful for your waiting logic. I've included it in the answer as well ;)
Working sample.

Related

Instant validation with optional function for number calculation with instant result

I want to show the error instantly until the request is filled right. It means that I want the user to get the number he is typing instantly without clicking the button...
Here is my code (also found on JSFiddle):
HTML:
<input type="number" id="myNumber" value="Error">
<button onclick="myFunction()">Click</button>
<p id="Error"></p>
JS:
window.myFunction = function() {
var err = " is not 1000!"
var num = document.getElementById("myNumber").value;
if (num == 1000) {
alert("No Errors!");
} else {
if (num !='') {
document.getElementById("Error").innerHTML = num+err;
}
else {
document.getElementById("Error").innerHTML = err;
}
}
}
I'm looking for a simple solution to use a function inside until the number is calculated, so to just show the "is not 1000" while typing something other than 1000 (like 1, 100, 1001 110011 etc..) can also be fine..
$("#myNumber").on("input",myFunction);
Dont wait for a click, but for an input. The upper is in jquery, pure js:
document
.getElementById("myNumber")
.addEventListener("input",myFunction);
or inline:
oninput="myFunction()"
you can call myFunction() on keyup event for your input box.
window.myFunction = function() {
var err = " is not 1000!"
var num = document.getElementById("myNumber").value;
if (num == 1000) {
alert("No Errors!");
document.getElementById("Error").innerHTML = "";
} else {
if (num !='') {
document.getElementById("Error").innerHTML = num+err;
}
else {
document.getElementById("Error").innerHTML = err;
}
}
}
<input type="number" id="myNumber" onkeyup="myFunction()" value="Error">
<button onclick="myFunction()">Click</button>
<p id="Error"></p>

How do I get the values in PROGRAM 2 to apply to printing in the console?

Okay so I technically have everything working in the program, but I need to permanently change the values of the array that I create in PROGRAM 2 and add -blip and -clang. What do I call upon to change the values so that I can call them to the console in PROGRAM 3? I can't have anything in the body so innerHTML and document.write are out of the question(which sucks). Problem area is marked with a comment on line 37 to make it easier to find.
<!DOCTYPE html>
<html>
<head>
<title>Project 1 – Michael Fiorello</title>
<p id="demo"></p>
<script>
do {
//MAIN MENU
var input = prompt("Please enter 1, 2, 3, or exit.");
{
//PROGRAM 1-Enter the string to be converted to robot speak
if (input === "1")
do {
var one = prompt ("Please enter a string.");
{
if (one === "")
{
console.warn("You need to enter something");
}
}
} while (one === "")//keep repeating program 1 until something is entered, aka cannot be blank.
//PROGRAM 2-Convert the string into robot speak
else if (input === "2")
{
if (one == null) {
console.warn ("You need to first enter a String");
}
else
{
console.log ("String Converted")
var res = one.split(" ");
for(i = 0; i<res.length; i++)
if(res[i].length >= 5)
//What do I do here to change the value of entered strings in the array, rather than just write it out?
{
document.write(res[i]+"-blip ");
}
else
{
document.write(res[i]+"-clang ");
}
}
}
//Program 3 Robot Language version of the string will appear in the console
else if (input === "3")
{
var output = res.join(" ");
alert ("AWESOME!");
console.log (output);
}
else if (input == null|| input.toLowerCase() == "exit")
{
alert ("Thanks for using the ROBOT Language Converter!");
}
else
{
alert ("Nope");
console.warn("You need to enter something");
}
}
} while(input.toLowerCase() != "exit");
</script>
</head>
</html>
It was so simple that I feel like an idiot. All I had to do was change the document.write lines to
res[i] = (res[i]+"-blip ");
and it changes the values to what I need.

Form not submitting in Jquery after user corrects errors (return false;)

I've ran into a pickle. I am writing a simple mortgage calculator that sends data to calc.php through ajax.
Using jquery, I am checking to make sure that the user enters the appropriate values in the requested fields; both purchase price and down payment should be numbers (working), down payment can't be greater than purchase price (working), when a term is selected, interest rate auto populates (working) and an error message appears if either term or interest rate aren't populated (working).
When user submits the form and any of the mandatory items are missing, error messages display advising... however, the form doesn't submit when errors are corrected by the user.
As you will soon see by looking at my not-too-sophisticated code, I am still learning Jquery and will appreciate any input you can give me.
Thanks in advance for the help.
HTML form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Calculator</title>
<link rel="stylesheet" type="text/css" href="css/css.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"> </script>
<script type="text/javascript" src="js/js.js" charset="utf-8"></script>
</head>
<body>
<h1>Mortgage</h1>
<form action="calc.php" method="post" id="mortgage-form">
<p class="errorMessage" id="shouldBeNumber">*This value can only contain numbers</p>
<p id="pPrice"><span class="errorMessage" id="PPmustBeNumber">*</span>Purchase Price:
<input type="text" name="purchase-price" id="purchase-price" value="0"/>
<span class="errorMessage" id="purchasePriceError">Please enter a number value!</span>
</p>
<p id="dPayment"><span class="errorMessage" id="DPmustBeNumber">*</span>Down Payment:
<input type="text" name="down-payment" id="down-payment" value="0"/>
<span class="errorMessage" id="downPaymentError">Down payment value must be less than Purchase Price!</span>
</p>
<p id="term">
<select id="loan-term">
<option value="noValueSelected">-- Select a Term -- </option>
<option value="15yrs">15 Years</option>
<option value="20yrs">20 Years</option>
<option value="30yrs">30 Years</option>
</select><span class="errorMessage" id="termRequired"> * Term is required.</span>
</p>
<div id="interest-rate"></div>
<p><input type="submit" name="submit" id="submit" value="Calculate!" /></p>
</form>
<footer>
<p>
© Copyright by Ricardo
</p>
</footer>
</body>
</html>
Here's my JQUERY
$(function() {
//HIDE errors
$('.errorMessage').hide();
//Do something when loan-term changes
$('#loan-term').change(function(){
var loanTerm = $(this).val();
var interestOption = '';
//alert(loanTerm);
if (loanTerm == '15yrs') {
interestOption += "<option value='15yrFixed'>15 Year Fixed: 2.88% </option>";
} else if (loanTerm == '20yrs') {
interestOption += "<option value='20yrFixed'>20 Year Fixed: 3.52%</option>";
} else if (loanTerm == '30yrs') {
interestOption += "<option value='30yrFixed'>30 Year Fixed: 4.2%</option>";
}
if (loanTerm != "noValueSelected") {
var interestRate =
"<select id='interest-rate'><option value='selectInterestRate'>-- Select an Interest Rate -- </option>" + interestOption + "</select><span class='errorMessage' id='interestRequired'> * This field is required.</span>";
$('#interest-rate').html(interestRate).show();
} else if (loanTerm == "noValueSelected") {
$('#interest-rate').hide();
}
});//END loan-term check
$('#mortgage-form').submit(function() {
var purchasePrice = $('#purchase-price').val();
var downPayment = $('#down-payment').val();
var loanTerm = $('#loan-term').val();
var interestRate = $('#interest-rate').val();
function containsNumber(val) {
return /^(\d|,)+$/.test(val)
}
if (containsNumber(purchasePrice) == true && containsNumber(downPayment) == true ) {
$('#PPmustBeNumber').hide();
$('#DPmustBeNumber').hide();
$('#shouldBeNumber').hide();
//alert(purchasePrice + downPayment);
//CHECK IF DOWNPAYMENT IS LESS THAN PURCHASE PRICE.
if (downPayment < purchasePrice) {
$('#downPaymentError').hide();
} else {
$('#downPaymentError').show();
}
} else if (containsNumber(purchasePrice) == false){
$('#PPmustBeNumber').show();
$('#shouldBeNumber').show();
} else if (containsNumber(downPayment) == false) {
$('#DPmustBeNumber').show();
$('#shouldBeNumber').show();
}
if (loanTerm != "noValueSelected") {
$('#termRequired').hide();
$("#interest-rate").change(function() {
if (interestRate != "selectInterestRate"){
$('#interestRequired').hide();
} else if (interestRate == "selectInterestRate"){
$('#interestRequired').show();
}
})
} else if (loanTerm == "noValueSelected"){
$('#termRequired').show();
}
if ( purchasePrice && downPayment && loanTerm && interestRate) {
var data = new Object();
data.purchasePrice = purchasePrice;
data.downPayment = downPayment;
data.loanTerm = loanTerm;
data.interestRate = interestRate;
data.interestOption = interestOption;
//create an object of Ajax options:
var options = new Object();
//Establish each setting:
options.data = data;
options.dataType= 'text';
options.type = 'get';
options.url = 'calc.php';
//perform the request:
$.ajax(options);
}
return false;
}); //END SUBMIT FUNCTION
});
I would just let the form submit as normal without doing the ajax. The primary issue I see is that you don't have a way for the form to return true; which allows the form to actually submit. Try subbing out your submit function for this below and that should get the ball rolling for you.
$('#mortgage-form').submit(function () {
var purchasePrice = $('#purchase-price').val();
var downPayment = $('#down-payment').val();
var loanTerm = $('#loan-term').val();
var interestRate = $('#interest-rate').val();
function containsNumber(val) {
return /^(\d|,)+$/.test(val)
}
if (containsNumber(purchasePrice) == true && containsNumber(downPayment) == true) {
$('#PPmustBeNumber').hide();
$('#DPmustBeNumber').hide();
$('#shouldBeNumber').hide();
//alert(purchasePrice + downPayment);
//CHECK IF DOWNPAYMENT IS LESS THAN PURCHASE PRICE.
if (downPayment < purchasePrice) {
$('#downPaymentError').hide();
} else {
$('#downPaymentError').show();
}
} else if (containsNumber(purchasePrice) == false) {
$('#PPmustBeNumber').show();
$('#shouldBeNumber').show();
} else if (containsNumber(downPayment) == false) {
$('#DPmustBeNumber').show();
$('#shouldBeNumber').show();
}
if (loanTerm != "noValueSelected") {
$('#termRequired').hide();
$("#interest-rate").change(function () {
if (interestRate != "selectInterestRate") {
$('#interestRequired').hide();
} else if (interestRate == "selectInterestRate") {
$('#interestRequired').show();
}
})
} else if (loanTerm == "noValueSelected") {
$('#termRequired').show();
}
if (purchasePrice && downPayment && loanTerm && interestRate) {
var data = new Object();
data.purchasePrice = purchasePrice;
data.downPayment = downPayment;
data.loanTerm = loanTerm;
data.interestRate = interestRate;
data.interestOption = interestOption;
//create an object of Ajax options:
var options = new Object();
//Establish each setting:
options.data = data;
options.dataType = 'text';
options.type = 'get';
options.url = 'calc.php';
return true;
}
return false;
}); //END SUBMIT FUNCTION
if you are using jQuery's ajax functions, you don't need to submit the form. Also, if you want the form to submit, you need to put in an IF function to return true, or it won't submit. Your code simply returns false no matter what. You need to make it conditional, so if the errors are not displayed because the criteria is met by the user, THEN the form returns true and sends, yet you wouldn't need the ajax then, as I have mentioned.
Sample code to validate with jQuery and submit the form normally:
For this to work, I would change the submit button from type="submit" to type="button" which will prevent it from submitting automatically.
$('#submit').click(function(){
// put all your code to check inputs for errors here.
$('#mortgage-form').submit();
});
This way you can use javascript for the validation and then send the form to the calc.php page just how you need it to work.
Ok, So instead of using AJAX, I changed my code to simple JQUERY validation and then normal form submission (which is what I wanted). I changed the form from GET to POST. I am still using JQUERY to validate the form, and then just send the values once everything is OK.
PHP will then handle the equations.
Thank you to everyone's suggestion; you inspired me to solve my issue.
Cheers!

Not Getting HTML TextBox Value in Javascript function? Have searched, but didn't find convincing answer

I'm a beginner trying to get the HTML from a textbox to be used in an if/else statement.
This is my HTML code:
<label id="label1">
Enter any Number:
</label>
<input type="button" id="Button1" value="button" />
<input type="text" id="TextBox1" name="myname" />
And my JavaScript code is:
<script type="text/javascript">
//<![CDATA[
var buttonElement = document.getElementById("Button1");
var txt_value =document.getElementById("TextBox1").value;
buttonElement.addEventListener('click', function() { Clicked(txt_value) }, false);
function Clicked(txt_value) {
if (txt_value == 7) {
alert("You are 7");
}
else { alert("You are not 7"); }
}
//]]>
</script>
I observed that
var txt_value =document.getElementById("TextBox1");
and then
buttonElement.addEventListener('click', function() { Clicked(txt_value.value) }, false);
The above example works absolutely fine.
Can someone please tell me what is wrong with:
var txt_value =document.getElementById("TextBox1").value;
I don't know why I'm getting an empty txt_value
The reason is that you are getting the value in txt_value before the user enters anything; hence the value is always empty.
IF you change your code to this:
var txt_value =document.getElementById("TextBox1");//removed .value
And the function Clicked to:
function Clicked(txt_value) {
if (txt_value.value == 7) { //added .value
alert("You are 7");
}
else { alert("You are not 7"); }
}
Should work.
Here's a jsfiddle
Move the getting of the value into the click handler...
var textbox1 = document.getElementById("TextBox1");
document.getElementById("Button1").onclick = function () {
var txt_value = textbox1.value;
if (parseInt(txt_value, 10) === 7) {
alert("You are 7");
} else {
alert("You are not 7");
}
};
Now you get the value that is in the textbox when the page loads.
Here is a JSFiddle to test this.
Update Improved the efficiency by caching the textbox. Removed the addEventListener to an onclick (more browser support)

search with jquery

I do a search by the js for my site.
Their code it might look like:
have a form and when the keyup event, it will send post to a file and retrieve data from that file into the html of a div crazy.
but this yourself in trouble. I find the example for "a" is about 3000 results. for example, take a second to send post. so I press "c" will now send the post to the file is "ac" and there are 100 such results takes 0.3 seconds.
eg time I press the letter "a" to "c" 0.2 seconds, it should show results "ac" at 0.5 seconds. then 0.5 seconds later it is the result of "a". ~> Find "ac" into finding "a"
So how do you now when you press "c" then it stopped send post with the value "a" that send post with value "ac".
<form method="post" onsubmit="return checkForm(this.form)">
<div class="search padding">
<input type="text" id="searchbox" name="manga_name" class="input" value="Tìm truyện muốn đọc ..." onfocus="if (value =='Tìm truyện muốn đọc ...'){value =''}" onblur="if (value ==''){value='Tìm truyện muốn đọc ...'}" />
<input type="submit" value=" " id="searchsubmit" class="go"/>
</div>
</form>
<div id="result"></div>
And the script:
<script>
$('#searchbox').keyup(function() {
search();
});
function search() {
var keyword = $('#searchbox').val();
if (keyword != "") {
$('#result').html(loadingText);
$('#result').css('display', 'block');
$.post('/search/',{"keyword":keyword}, function(data){
if (data != "")
{
$('#result').html(data);
}
else
{
$('#result').html('');
$('#result').css('display', 'none');
}
});
}
else {
$('#result').html('');
$('#result').css('display', 'none');
}
}
</script>
// use to delay the callback execution
// so your search will be executed only you stop typing after 0.5(500 ms for example) second
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout(timer);
timer = setTimeout(function() {
callback();
}, ms);
}
}());
$('#searchbox').keyup(delay(search, 500));
You may try;
var timer = null;
$("#text_box").keyup(function() {
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(search, 1000);
});
There is a similar question here that I asked before. Always do a search in stackoverflow before posting a question.

Categories