if/else statement confusion - javascript

I'm thinking about making a small semi-game where you respond to a mysterious void about things. The user sees a question on-screen, types a response in the textbox and clicks the reply button, and the script replies.
My main problem is to understand the logic behind all this.
For example:
Do you like apples?
A1:Yes
A2:No
if(yes){
say this
} else if(no){
say that
}
What would be the appropriate syntax in this case? Because i'm really really confused right now, it may seem like a very noob-question, but jQuery is getting on my nerves.

var input = document.querySelector('input'),
output = document.getElementById('output');
input.onkeyup = function(event) {
switch (this.value.toLowerCase()) {
case 'chicken':
output.innerText = "I like chicken too";
break;
case 'meat':
output.innerText = "mmmmm, meat!!";
break;
default:
break;
}
};
<form>
<input type="text" />
<div id="output">Huh?</div>
</form>
You could also just do this
var isYes = true;
(isYes) ? /* Do this */ : /* Do this */ ;
Saves you lines of code
Edit: As you had requested I have created a snippet. Try it out, type in chicken/meat

Since you are using a Boolean (true,false) type of scenario you can can just use an if/else type of statement:
var is_yes = true;
if(is_yes){
// Do this
} else {
// Do that
}

Related

Inserting button with function? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Here is my code:
function ayee() {
confirm("Ready to play?");
var age = prompt("How old are you?"),
replacement = document.getElementById('container'),
message;
if (age >= 18) {
message = "Let's get started!" ;
} else {
message = "You're under 18? Be careful out there....";
}
replacement.innerHTML = message ;
}
What I want to do is in the return if age is greater then 18, add a button along with the message(or containing the message) that on click will send into the next function.
PS: this is for a choose your own adventure game.
try this
replacement.innerHTML = message+"<button>Next</button>"
var s = replacement.getElementsByTagName("button")[0];
s.addEventListener("click",function() {alert("next");}) // change the function to
// suit your needs
The idea is innerHTML creates the DOM. You can then use normal JavaScript function getElementsByTagName to get the button inside your replacement
Then add an event listener on the click of the button using addEventListener
This will work only on modern browsers. To make it work in IE prior to IE9 please add the following code. See the following link for more details
if(s.addEventListener)
s.addEventListener("click",myFunction);
else if (s.attachEvent)
s.attachEvent("click", myFunction);
fiddle
Write your function with some param
function myfunction(message){
//do something with message
}
and change message = "Let's get started!" ; to myfunction('Let's get started!')
Do something like this:
var btn = document.createElement("button");
btn.value = "Begin";
if (age >= 18) {
btn.addEventListener("click", function() {
eighteen();
});
}
else {
btn.addEventListener("click", function() {
notEighteen();
});
}
container.appendChild(btn):
You could also call one generic function that checks the age and runs two different sections of code instead of adding event listeners for two different functions.
Just a note: when you declare a variable, you should place "var" behind it. (var a = "test";.)
attach a button, alongside your html to be displayed, and add a click handler to the button with the function you want to trigger when the button is clicked, for example a simple code can be like:
function ayee() {
confirm("Ready to play?");
var age = prompt("How old are you?"),
replacement = document.getElementById('container'),
message;
if (age >= 18) {
//create a button
var btn = "<input type='button' name='test' onclick='checkThis();' value='Click'>";
//add the button to the message
message = "Let's get started!" + btn ;
} else {
message = "You're under 18? Be careful out there....";
}
replacement.innerHTML = message ;
}
function checkThis() {
alert("Clicked the button");
}

Trying to change the color of text on click in javascript

So I am trying to make something where whenever I click on the text it change's color.
Javascript:
function changecolor(){
var tc = document.getElementById("header").style.color.value;
if (tc = "#000000") { tc = "#0009FF"}
else if (tc == "#0009FF") { tc = "#FF0000"}
else if (tc == "#FF0000") { tc = "#15FF00"}
else if (tc == "#15FF00") { tc = "#FFA600"}
else {tc = "#000000"};
document.getElementById("header").style.color.value = tc;
}
html:
<div onclick="changecolor()"><h1 id="header" style="color:#000000;"> Nick's Basic Physic's Calculator </h1></div>
It is not working and I have not been able to figure out why. When I click on the text nothing happens.
Change
document.getElementById("header").style.color.value = tc;
to
document.getElementById("header").style.color = tc;
Working example:
http://jsfiddle.net/xEyLf/
your problem is in var tc = document.getElementById("header").style.color.value;
you have to change to tc = document.getElementById("header").style.color;in order to get the color into variable.
I have another solution... here's a jsfiddle: http://jsfiddle.net/9zfJA/
Keep in mind I'm using these jQuery methods (as well as the jQuery library itself), by simply switching between CSS classes:
hasClass(): to check if the class is present
addClass(): to add the correct class based on the condition above
removeClass(): remove all classes, I've basically built a "reset" function
I think there are errors in the way it functions and how you want it, but I've built it on the same logic you have in your question.

Replacing Document.write Problems(I did some research but still failed)

I got a great answer to this but have more questions. :) I was told that having javascript declared in two different places was bad and messy(you can see in the answer below), but I'm learning from a book right now and it told me to put my variables, arrays, functions etc. in the head of the html and the rest in the body.(that's why I have javascript declared in two different places) Is that wrong and why? He also recommended using a developer tool. I'm very new to coding in general and don't know much about these could anyone recommend a developer tool for chrome? Also what would a developer tool do? Thanks!
This was fixed:
Hi I was converting the card war game so it worked on a page instead of in the console and here was my original code http://pastebin.com/AgLgy97F. I was trying to use document.write to write out the code on a web, but I found out that document.write rewrote the whole page and removed the button I put there to progress to the next turn.
I looked on the forums and I looked online and came to the conclusion that I shoud replace it using this<div id="play"></div> and document.getElementById("play").innerHTML="I'm a string!". So I made this http://pastebin.com/29mVqp67. I tried it out and nothing happened -_-. What did I do wrong replacing document.write?
The new code I made is here too:
<html>
<head>
<script language="JavaScript">
<!--
var disp = function() {
document.getElementByID("play").innerHTML="You drew a "+user_disp+".";
document.getElementByID("play").innerHTML="Your opponent drew a "+cpu_disp+".";
document.getElementByID("play").innerHTML=statement;
};
var war = function() {
document.getElementByID("play").innerHTML="W-A-R spells WAR!";
disp();
};
var full = [1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,11,11,11,11,12,12,12,12,13,13,13,13];
var user = [];
var cpu = [];
var rand = 0;
//Shuffles and deals the deck
var shuffled = [];
for (var i=0;i<52;i++) {
rand=Math.floor(Math.random()*full.length);
shuffled.push(full[rand]);
full.splice(rand,1);
}
for (var j=0;j<52;j++) {
if (j%2===0) {
user[user.length]=shuffled.pop();
} else {
cpu[cpu.length]=shuffled.pop();
}
}
//Creates a bunch of variables and functions that will be needed in the game
var cpu_card=0;
var cpu_warcard=0;
var cpu_war1=0;
var cpu_war2=0;
var cpu_war3=0;
var cpu_disp=0;
var user_card=0;
var user_warcard=0;
var user_war1=0;
var user_war2=0;
var user_war3=0;
var user_disp=0;
var statement=0;
var card_name = function(cpuc,userc) {
switch (cpuc) {
case 13:
cpu_disp="K";
break;
case 12:
cpu_disp="Q";
break;
case 11:
cpu_disp="J";
break;
case 1:
cpu_disp="A";
break;
default:
cpu_disp=cpuc;
break;
}
switch (userc) {
case 13:
user_disp="K";
break;
case 12:
user_disp="Q";
break;
case 11:
user_disp="J";
break;
case 1:
user_disp="A";
break;
default:
user_disp=userc;
break;
}
};
//Lets play the game!
//-->
</script>
</head>
<body>
<form>
<input type="Button" value="Click to Take Your Turn" onClick="playWar()"></input>
</form>
<p>
<h1>This Is War Lets Play!!!!</h1>
<br>
<div id="play"></div>
<script language="JavaScript">
<!--
function playWar(){
if(user.length<52 && user.length>1) {
//Picks out the cards that are used
cpu_card=cpu.shift();
user_card=user.shift();
card_name(cpu_card,user_card);
//Figures out if you win, lose, or go to war
if (user_card<cpu_card) {
statement="You lost!";
cpu[cpu.length]=cpu_card;
cpu[cpu.length]=user_card;
} else {
if (user_card>cpu_card) {
statement="You won!";
user[user.length]=user_card;
user[user.length]=cpu_card;
} else {
if(cpu.length<3 || user.length<3){
user[user.length]=user_card;
cpu[cpu.length]=cpu_card;
}
else{
statement="You tied! TO WAR!";
}
}
}
disp();
//This is what happens when you go to war
if (statement==="You tied! TO WAR!") {
cpu_war1=cpu.shift();
cpu_war2=cpu.shift();
cpu_war3=cpu.shift();
cpu_warcard=cpu.shift();
user_war1=user.shift();
user_war2=user.shift();
user_war3=user.shift();
user_warcard=user.shift();
card_name(cpu_warcard,user_warcard);
if (user_warcard<cpu_warcard) {
statement="You lost the war to your opponent!";
cpu[cpu.length]=cpu_war1;
cpu[cpu.length]=cpu_war2;
cpu[cpu.length]=cpu_war3;
cpu[cpu.length]=cpu_warcard;
cpu[cpu.length]=cpu_card;
cpu[cpu.length]=user_war1;
cpu[cpu.length]=user_war2;
cpu[cpu.length]=user_war3;
cpu[cpu.length]=user_warcard;
cpu[cpu.length]=cpu_card;
} else {
if(user_warcard>cpu_warcard) {
statement="You crushed your opponent in war!";
user[user.length]=user_war1;
user[user.length]=user_war2;
user[user.length]=user_war3;
user[user.length]=user_warcard;
user[user.length]=user_card;
user[user.length]=cpu_war1;
user[user.length]=cpu_war2;
user[user.length]=cpu_war3;
user[user.length]=cpu_warcard;
user[user.length]=cpu_card;
} else {
statement="The war resulted in a stalemate!";
user[user.length]=user_war1;
user[user.length]=user_war2;
user[user.length]=user_war3;
user[user.length]=user_warcard;
user[user.length]=user_card;
cpu[cpu.length]=cpu_war1;
cpu[cpu.length]=cpu_war2;
cpu[cpu.length]=cpu_war3;
cpu[cpu.length]=cpu_warcard;
cpu[cpu.length]=cpu_card;
}
}
war();
}
}
//When you are done, here it finds if you win or lose this game
else if (user.length===52) {
document.getElementByID("play").innerHTML="You have crushed your opponent. Feel free to steal all of his belongings!";
} else {
document.getElementByID("play").innerHTML="Unfortunatly, you have fallen victim to your opponent's wrath and have been conquered.;
}
}
//-->
</script>
</body>
You have a few problems here to start with.
you have your javascript declared in two different places and in both cases you are polluting the global namespace. That should be cleaned up and may help identify some problems.
you have an unterminated string literal at the end of this line:
you have fallen victim to your opponent's wrath and have been conquered. <===
getElementByID NEEDS to be getElementById
Your disp() function is incorrect. As it is written, each successive line is replacing the previous text.
var disp = function() {
document.getElementByID("play").innerHTML="You drew a "+user_disp+".";
document.getElementByID("play").innerHTML="Your opponent drew a "+cpu_disp+".";
document.getElementByID("play").innerHTML=statement;
};
This can be fixed by concatenating the strings together prior to setting innerHtml, or, to have more control over the output you can use separate elements. Pseudo code:
else.innerHTML = string1 + string2 + string3;
I'd recommend making some heavy use of the developer tools for whichever browser you are using for development. It will help you catch many of these problems either by watching the console output or by stepping through the code.
I've put your code in a jsFiddle as well.
That should get you started. Good luck!

how do you make a text input field open different links based on user input

I can't imagine this is very hard but i've been trying to figure out the best way to do this and honestly im completely lost. Now im getting frustrated so it would be great if someone who knows how to do this exactly could help me out.
I need a textbox I can embed into my html script, that will open different links depending on the users input text.
So in english here is the basics of what I need. A working script would be very much appreciated for I am stumped.
* stands for “any characters”
If text input contains bbb open link htttp://example1.com/bbb
otherwise
If text input contains *zzz* open link htttp://example2.com/something-predefined*zzz*
otherwise
If text input contains *xxx* open link htttp://example3.com/something-predefined*xxx*
otherwise
If text input contains * open link htttp://example3.com/*
Pseudocode:
function parmatch(input):
if input matches /^bbb$/
open 'http://example1.com/{input}'
return
if input matches /zzz/
open 'http://example2.com/something-predefined{input}'
return
if input matches /xxx/
open 'http://example3.com/something-predefined{input}'
return
MDN's article on regular expressions in JavaScript
the following code only example for what you ask. here change the <a href=""> for console.
<input type="text" id="picker" />
$('#picker').keyup(function() {
var value = $("#picker").val();
if(value == "1")
{
console.log("go to home");
}
else if(value == "2")
{
console.log("go to login");
}
else
alert("plz enter valid input");
})
For a more complete answer, I'd suggest the following:
var btn = document.getElementById('fire'),
input = document.getElementById('demo'),
output = document.getElementById('output'),
pageMap = {
'aaa' : 'pageA',
'bbb' : 'pageB',
'ccc' : 'pageC'
};
function loadPage (input, output, map) {
var v = input.value,
url = 'http://example.com/',
text = 'textContent' in document ? 'textContent' : 'innerText';
for (var i in map) {
if (map.hasOwnProperty(i) && v.indexOf(i) > -1) {
// the following shows the URL you'd end up with
output[text] = url + map[i];
// to *load* the URL, remove the above line,
// and uncomment the following:
// window.location = url + map[i];
}
}
}
btn.addEventListener('click', function(e){
e.preventDefault();
loadPage(input, output, pageMap);
});
JS Fiddle demo.
This answer is, however, not to encourage you to avoid learning JavaScript (as suggested in the comments to Ignacio's answer); please take the time to read, at least, the references I've supplied below.
References:
document.getElementById().
Element.addEventListener().
event.preventDefault().
for...in loop.
JavaScript object syntax.
window.location.

addition in while( )

Here is the HTML:
<form>
<textarea id="input1"></textarea>
<textarea id="input2"></textarea>
<span></span>
</form>
the js:
$("#input2").keyup{
var a = document.getElementById("input1").length;
var b = document.getElementById("input2").length;
var c=a+b;
$("span").html(c);
}
each time 'c' reach multiple 140, i need it to be added by 'b',
I've try to do this:
while(c%140 == 0){
c=c+b;
}
at 140th keyup, yes its added, but next keyup(141th) and so on 'c' back to it's value added by notihng. How to do this correctly?
thanks.
I can't be sure that I'm reading this question correctly, but if my jsfiddle of your code is a close approximation, the solution may be as simple as getting rid of the var in front of c when you add a+b. If you want c to have a persistant value, you need its scope to be outside the keyup event handler.
From the fiddle:
$(function() {
var c = 0;
$("#input2").keyup( function() {
var a = $("#input1").val().length;
var b = $("#input2").val().length;
c=a+b;
if(c%140 == 0){
c=c+b;
}
$("span").html(b);
});
});
Notice that's an if, not a while. If it's supposed to be a while loop, that's an easy change to make.
Update
I think I have an idea what's going on here. You want to keep track of the total character count of your multi-page SMS messages. The updated jsfiddle has the answer to the question you wouldn't just come out and ask.
Here's the new code:
$(function() {
$("#input2, #input1").keyup( function() {
var a = $("#input1").val().length;
var b = $("#input2").val().length;
c=a+b;
c+=Math.floor(c/140)*b;
$("span").html(c);
});
});
Now, this of course assumes that input1 holds your actual message while input2 holds some text that needs to be displayed on each page. If it's the other way around, or if there's some other purpose for this code, please let me know.

Categories

Resources