Create switch based on dropdown menu - javascript

I am trying to create a normal javascript switch that'll give me an alert message and image based on what the user has selected from a drop down menu
here's what I have so far
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<h1>How are you feeling?</h1>
<img id="feelimg" src="Images/questionSun.jpg" alt="question sun">
<select id="feeling" onChange="changeFeeling();">
<option value="question">Question</option>
<option value="happy">Happy</option>
<option value="sad">Sad</option>
<option value="cool">Cool</option>
<option value="unsure">Unsure</option>
</select>
<script type="text/javascript">
var curFeel = document.getElementById('feeling').value;
function changeFeeling(){
switch (curFeel) {
case 'question': {
document.getElementById("feelimg").src = "Images/questionSun.jpg";
alert("Please make a selection or go back to bed!");
break;
}
case 'happy': {
document.getElementById("feelimg").src = "Images/happySun.jpg";
alert("I am glad you are happy");
return curFeel;
break;
}
case 'sad': {
document.getElementById("feelimg").src = "Images/sadSun.jpg";
alert("I am sorry you are sad");
break;
}
case 'cool': {
document.getElementById("feelimg").src = "Images/coolSun.jpg";
alert("It's great you are feeling cool!");
break;
}
case 'unsure': {
document.getElementById("feelimg").src = "Images/unsureSun.jpg";
alert("I hope you get past that soon!");
break;
}
}
}
</script>
</body>
</html>
No matter what I do it is stuck on case question. It needs to be javascript. I am not allowed to use jquery for this particular problem.

Just move your var declaration inside your function.
The way you have done the var was getting populated with the value once the javascript gets loaded, moving it to the function it will be populated at the onChange event and then the switch works nice.
<script type="text/javascript">
var curFeel = document.getElementById('feeling').value;
function changeFeeling(){
curFeel = document.getElementById('feeling').value;
switch (curFeel) {
case 'question': {
document.getElementById("feelimg").src = "Images/questionSun.jpg";
alert("Please make a selection or go back to bed!");
break;
}
case 'happy': {
document.getElementById("feelimg").src = "Images/happySun.jpg";
alert("I am glad you are happy");
return curFeel;
break;
}
case 'sad': {
document.getElementById("feelimg").src = "Images/sadSun.jpg";
alert("I am sorry you are sad");
break;
}
case 'cool': {
document.getElementById("feelimg").src = "Images/coolSun.jpg";
alert("It's great you are feeling cool!");
break;
}
case 'unsure': {
document.getElementById("feelimg").src = "Images/unsureSun.jpg";
alert("I hope you get past that soon!");
break;
}
}
}
</script>
Another way that I would recomend is to not use this global variable and just use the parameter using the onchange like that:
<select id="feeling" onChange="changeFeeling(this);">
<option value="question">Question</option>
<option value="happy">Happy</option>
<option value="sad">Sad</option>
<option value="cool">Cool</option>
<option value="unsure">Unsure</option>
</select>
<script type="text/javascript">
function changeFeeling(curFeel){
switch (curFeel.value) {
case 'question': {
document.getElementById("feelimg").src = "Images/questionSun.jpg";
alert("Please make a selection or go back to bed!");
break;
}
case 'happy': {
document.getElementById("feelimg").src = "Images/happySun.jpg";
alert("I am glad you are happy");
return curFeel;
break;
}
case 'sad': {
document.getElementById("feelimg").src = "Images/sadSun.jpg";
alert("I am sorry you are sad");
break;
}
case 'cool': {
document.getElementById("feelimg").src = "Images/coolSun.jpg";
alert("It's great you are feeling cool!");
break;
}
case 'unsure': {
document.getElementById("feelimg").src = "Images/unsureSun.jpg";
alert("I hope you get past that soon!");
break;
}
}
}
</script>

Make your switch variable event.target.value and it will work how you want it to.
To access a global var from inside a function
var curFeel;
function changeFeeling(){
curFeel = event.target.value;
switch (curFeel) {
case 'question': {
....
}
}
}
That way the variable curFeel will be whatever the selected value is globally.
Heres a Codepen

I think Diego Garcia has provided the answer, but I'd like to suggest a simple improvement to the code generally for you to collect a few bonus points (should they be available).
var curFeel; // Value is not being used before changeFeeling function call, so you only need declare it rather than assign a value
function changeFeeling(){
var picture, message; // Declare variables to contain the decided upon image and alert message
var pictureFiles = 'Images/'; // Where your image files are kept, so you don't repeat a dozen times below
curFeel = document.getElementById('feeling').value;
switch (curFeel) {
case 'question': {
picture = "questionSun.jpg";
message = "Please make a selection or go back to bed!";
break;
}
case 'happy': {
picture = "happySun.jpg";
message = "I am glad you are happy";
break;
}
case 'sad': {
picture = "sadSun.jpg";
message = "I am sorry you are sad";
break;
}
case 'cool': {
picture = "coolSun.jpg";
message = "It's great you are feeling cool!";
break;
}
case 'unsure': {
picture = "unsureSun.jpg";
message = "I hope you get past that soon!";
break;
}
}
// Set image and alert message!
document.getElementById("feelimg").src(pictureFiles + picture);
alert(message);
}
Reasons Why:
The above is easier to read
In the event that the ID of the picture element, or the location of the image files, changes you only need to change it in one place rather than a dozen
And the same if the behaviour around the message alert changes, e.g. instead of using the alert() function, the message is inserted into a div element on the page instead for example (only one change required rather than a dozen)
Hope this helps.

Related

Change Attribut when Specific Option is Selected in Dropdown List

So there is my following code :
index.html
<img id="crypto-pic" src="./assets/img/cryptos/btc.png" alt="crypto" height="15" width="15">
<select id="input-crypto" class="form-control">
<option value="bitcoin">Bitcoin</option>
<option value="ethereum">Ethereum</option>
...
...
...
</select>
script.js :
if($("#input-crypto option:selected").text() == bitcoin){
$('#crypto-pic').attr('src', './assets/img/cryptos/btc.png');
};
if($("#input-crypto option:selected").text() == ethereum){
$('#crypto-pic').attr('src', './assets/img/cryptos/eth.png');
};
The fact is that when Ethereum is selected in the list, the image don't change to eth.png.
Can you help me please, thanks.
I'd use an onChange event, and a switch statement for less code and more flexibility
$("#input-crypto").on("change", function(){
var imgSrc;
switch($(this).val()) {
case "ethereum":
imgSrc = './assets/img/cryptos/eth.png';
break;
case "anotherOption1":
imgSrc = './assets/img/cryptos/xxx.png';
break;
case "anotherOption2":
imgSrc = './assets/img/cryptos/xxx.png';
break;
default:
imgSrc = './assets/img/cryptos/btc.png';
}
$('#crypto-pic').attr('src', imgSrc);
});
You have missed single or double quotes around bitcoin and ethereum. Also if you are running the scripts without any function call or listener, it wont work.
For your better understanding, track the change of selection using .change() function and then check the latest selected value.
$("#input-crypto").change(function(){
if($("#input-crypto").val() == "bitcoin"){
$('#crypto-pic').attr('src', './assets/img/cryptos/btc.png');
};
if($("#input-crypto").val() == "ethereum"){
$('#crypto-pic').attr('src', './assets/img/cryptos/eth.png');
};
});
You can use .on() function to achieve it.
$('#input-crypto').on('change', function () {
var selectedOption = $(this).val();
if (selectedOption == "bitcoin") {
$('#crypto-pic').attr('src', './Content/img/cryptos/btc.png');
}
if (selectedOption == "ethereum") {
$('#crypto-pic').attr('src', './assets/img/cryptos/eth.png');
}
});

Javascript - Ignore punctuation and spaces in a Switch Statement

I have a page with a question. The user will have to type the answer to that question in a textbox. I am using a switch statement to generate different feedback to different answers. I already managed to make it case insensitive.
Is there a way to also make it ignore punctuation and spaces?
This is the code I have:
function myFunction() {
var text;
var answers = document.getElementById("myInput").value.toLowerCase();
switch (answers) {
case "superman":
text = "That is correct!";
break;
case "batman":
text = "You must be kidding me...";
break;
default:
text = "Wrong answer."
}
document.getElementById("comment").innerHTML = text;
}
<p>Who is Clark Kent?</p>
<input id="myInput" type="text">
<button onclick="myFunction()">Answer</button>
<p id="comment"></p>
I would like it to accept all the following answers as correct, without having to add extra cases:
"Superman", "superman", "Super Man", "Super man", "Super-Man!", "Super-man"...
You could use a regex to ignore everything else that is not an alphabet.
function myFunction() {
var text;
var answers = document.getElementById("myInput").value.toLowerCase();
answers = answers.replace(/[^a-z]/g, "");
switch (answers) {
case "superman":
text = "That is correct!";
break;
case "batman":
text = "You must be kidding me...";
break;
default:
text = "Wrong answer."
}
document.getElementById("comment").innerHTML = text;
}
You could match only letters and omit unwanted character. Then take convert to lower case.
function myFunction() {
function getLetters(s) { return s.match(/[a-z]/gi).join('').toLowerCase(); }
var text;
var answers = document.getElementById("myInput").value.toLowerCase();
switch (getLetters(answers)) {
case "superman":
text = "That is correct!";
break;
case "batman":
text = "You must be kidding me...";
break;
default:
text = "Wrong answer."
}
document.getElementById("comment").innerHTML = text;
}
<p>Who is Clark Kent?</p>
<input id="myInput" type="text">
<button onclick="myFunction()">Answer</button>
<p id="comment"></p>
use this:
var desired = stringToReplace.replace(/[^\w\s]/gi, '').toLowerCase();

Case not working on second input?

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.

Using an external file on a button in html

<button onclick = "button javascript.js">
What do you drive? </button>
I want the button to run my switch() in the button javascript.js file
var car = prompt('What car?');
switch(car) {
case 'ferrari':
document.write("you are probs a baller then");
break;
case "porsche":
document.write("do you ball hard?");
break;
case "dodge":
document.write("american cannot corner");
break;
default:
document.write("your car better be a subaru");
}
You can put the code in a function inside the javascript. Include the file in script tags and on click of the button, call that function. That will trigger the JS code only on click of the button.
Put this in the HTML,
<script src='button javascript.js'></script>
//Intermediate HTML code
<button onclick = "myButtonFun()">
What do you drive? </button>
And in the Javascript you can put in your code in the function myButtonFun()
function myButtonFun()
{
var car = prompt('What car?');
switch(car) {
case 'ferrari': document.write("you are probs a baller then");
break;
case "porsche": document.write("do you ball hard?");
break;
case "dodge": document.write("american cannot corner");
break;
default: document.write("your car better be a subaru");
}
}
Make your code into a function and, on the button, use
type="button"
and
onclick="yourFunction()"
You need to wrap your script into function and invoke it on button click:
<button onclick = "askForCar();">What do you drive?</button>
var askForCar = function() {
//you script here
};
var askCar = function() {
switch (prompt('What car?')) {
case 'ferrari':
document.write("you are probs a baller then");
break;
case "porsche":
document.write("do you ball hard?");
break;
case "dodge":
document.write("american cannot corner");
break;
default:
document.write("your car better be a subaru");
}
};
<button onclick="askCar();">What do you drive?</button>

Why doesn't my switch statement work?

Somehow I figure the "this" keyword isn't paying reference to the value. However as you know I could use continual if/else if statements and it will work just fine. For example I could write the code this way.
if(painStatus == 1) {
msg.innerHTML = "pain message 1";
}
else if(painStatus == 2) {
msg.innerHTML = "pain message 2";
}
so on and so forth, but using a switch statement it fails on me. I'm sure it is something simple I am not doing right. Sorry for being a noob.
<head>
<script type="text/javascript">
function painLevel(val) {
var painStatus = document.getElementById("pain_status").innerHTML = val;
var msg = document.getElementById("painMsg");
switch (painStatus) {
case 1:
msg.innerHTML = "Pain message 1";
break;
case 2:
msg.innerHTML = "Pain message 2";
break;
.
.
.
default:
msg.innerHTML = "";
}
}
</script>
</head>
<body>
<p>Please use the bar to select pain level</p>
<p>My Pain Level</p>
<input type = "range" min="0" max="10" value="1" onchange="painLevel(this.value)" />
Pain Level = <span id="pain_status">1</span>
<br /><br />
<div id="painMsg"> rePain message 1</div>
</body>
I believe you just need to parseInt like this
switch (parseInt(painStatus)) {
// As before....
}

Categories