var deviceName = '';
if(deviceName == 'sampleOne'){
newName = 'One'
}
if(deviceName == 'sampleTwo'){
newName = 'Two'
}
if(deviceName == 'sampletThree'){
newName = 'Three'
}
I have this simple if statement for Javascript.
How it works?
When a data inputed is sampleOne the output will be One. That's it, very simple right?
Take note that this code is working fine. But my problem is I have so many sample and I think using this kind of If statement is a bad idea because it will be too long. Is there a way to shorten this if statament?
If you have a lot of these you can make an object that maps the deviceName to the newName. Then you can just look it up:
let lookup = {
'sampleOne': 'One',
'sampleTwo': 'Two' ,
'sampleThree': 'Three'
}
let deviceName = 'sampleTwo'
let newname = lookup[deviceName]
console.log(newname)
You can use switch statement:
var deviceName = 'sampleFour';
var newName;
switch (deviceName) {
case 'sampleOne':
newName = 'One';
break;
case 'sampleTwo':
newName = 'Two';
break;
case 'sampleThree':
newName = 'Three';
break;
case 'sampleFour':
newName = 'Four';
break;
case 'sampleFive':
newName = 'Five';
}
console.log(newName);
var deviceName = "sampleOne";
newName =deviceName.split('sample')[1];
console.log(newName );
If your value starts with sample just use this logic
You can use switch statement. Find an example below:
<html>
<body>
<input id="myInput" type="text">
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var text;
var deviceName = document.getElementById("myInput").value;
switch(deviceName ) {
case "sampleOne":
text = "One";
break;
case "sampleTwo":
text = "Two";
break;
case "sampletThree":
text = "Three";
break;
default:
text = "No Match";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
You can also use a Switch instead of IF condition. Switch can be used if you want to do multiple operations in conditions.
var deviceName = 'sampleOne';
switch(deviceName)
{
case 'sampleOne':
newName = 'One';
break;
case 'sampleTwo':
newName ='Two';
break;
case 'sampleThree':
newName ='Three';
break;
default:
break;
}
Related
I have multiple variables that use arguments to calculate an answer, but it only seems to work when I have a single variable with arguments.
My HTML is:
<textarea id="given" placeholder="Given"></textarea>
<input type="text" id="result" placeholder="Result" list="resultAutoComplete"/>
<datalist id="resultAutoComplete">
<option value="v">(v) Speed</option>
<option value="ρ">(ρ) density</option>
<option value="Eₚ">(Eₚ) Potential energy</option>
</datalist>
<button type="button" onClick="calculateAnswer();">result</button>
<p><a id="Rho" onClick="RhoAdd();" style="cursor: pointer;">ρ</a></p>
<button id="Example" onClick="Examplefill();" style="cursor: pointer;">ρ</button>
<p>Answer: <b id="answer"></b></p>
<div style="background-color: #ACACAC; width: 100%;"><ins style="color: #ED141A; font-size: 20px; margin-left: 5px;" id="errorAlerts"></ins></div>
When I get rid of other variables: ress and rest it works.
Here's what worked
function calculateAnswer() {
var givenInput = document.getElementById('given').value;
var road_s = givenInput.match(/s=(.*)(;)/); //looks for S= (road)
var time_t = givenInput.match(/t=(.*)(;)/); //looks for t= (time)
var speed_v = givenInput.match(/v=(.*)(;)/); //looks for v= (speed)
var toFind = document.getElementById('result').value;
var resv = road_s[1] / time_t[1];
if (toFind === "v") {
document.getElementById('answer').innerHTML = resv;
document.getElementById('errorAlerts').innerHTML = "";
} else {
document.getElementById('errorAlerts').innerHTML = "ERROR... invalid requested result";
}
}
I need this to print out a answer using road_s[1], time_t[1] and speed_v[1], but when I add more variables using these arguments
var resv = road_s[1] / time_t[1];
var ress = speed_v[1] * time_t[1];
var rest = road_s[1] / speed_v[1];
the system doesn't print out anything
function calculateAnswer() {
var givenInput = document.getElementById('given').value;
var road_s = givenInput.match(/s=(.*)(;)/); //looks for S= (road)
var time_t = givenInput.match(/t=(.*)(;)/); //looks for t= (time)
var speed_v = givenInput.match(/v=(.*)(;)/); //looks for v= (speed)
var toFind = document.getElementById('result').value;
var resv = road_s[1] / time_t[1];
var ress = speed_v[1] * time_t[1];
var rest = road_s[1] / speed_v[1];
if (toFind === "v") {
document.getElementById('answer').innerHTML = resv;
document.getElementById('errorAlerts').innerHTML = "";
} else {
document.getElementById('errorAlerts').innerHTML = "ERROR... invalid requested result";
}
if (toFind === "s") {
document.getElementById('answer').innerHTML = ress;
document.getElementById('errorAlerts').innerHTML = "";
} else {
document.getElementById('errorAlerts').innerHTML = "ERROR... invalid requested result";
}
if (toFind === "t") {
document.getElementById('answer').innerHTML = rest;
document.getElementById('errorAlerts').innerHTML = "";
} else {
document.getElementById('errorAlerts').innerHTML = "ERROR... invalid requested result";
}
}
It's is very hard to explain because I'm not very familiar with arguments.
So, there are a few things going on here. First, when you match your regex (given the input you've commented), you will always have one of the three that doesn't match. Given the comment input, speed_v will be null, and would cause a fatal error in two of the three equations. At the first fatal error, the program would halt.
To fix this, I changed your match statements a little:
var road_s = givenInput.match(/s=(.*)(;)/) || [null, 0]; //looks for S= (road)
var time_t = givenInput.match(/t=(.*)(;)/) || [null, 0]; //looks for t= (time)
var speed_v = givenInput.match(/v=(.*)(;)/) || [null, 0]; //looks for v= (speed)
In each case, if match returns null, the || operator (logical or) kicks in, and creates a 'dummy array', containing [null, 0] - thus providing a value for the missing option, each time.
The second problem you encounter is in your if statement. In each branch, you say 'if the chosen option is thus-and-such, display the calculation. if not, show an error!' And that is happening for each of the various options.
A better approach may be to use a switch statement, allowing you to watch for each possible outcome:
switch(toFind){
case 'v':
document.getElementById('answer').innerHTML = resv;
document.getElementById('errorAlerts').innerHTML = "";
break;
case 's':
document.getElementById('answer').innerHTML = ress;
document.getElementById('errorAlerts').innerHTML = "";
break;
case 't':
document.getElementById('answer').innerHTML = rest;
document.getElementById('errorAlerts').innerHTML = "";
break;
default:
document.getElementById('errorAlerts').innerHTML = "ERROR... invalid requested result";
}
To see this as a working solution, take a look at this repl: https://repl.it/#TobiasParent/tooManyArgsSO
edit: I know this is a hacky solution, but let's face it - the HTML is hacky, the input is hacky, the whole thing has a slap-dash feel. Given that, this is a teachable moment. Learn about the switch/case branching mechanism, and try to understand why you were getting a fatal error in your calculations.
Still getting the hang of Javascript so forgive me if this seems like basic stuff.
I've set up a slider on a web page and the CSS/HTML function perfectly but I'm trying to display a year value to correspond with each value of the slider from 1 to 6.
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = 133;
slider.oninput = function() {
switch (this.value) {
case 1:
output.innerHTML = 133;
break;
case 2:
output.innerHTML = 88;
break;
case 3:
output.innerHTML = 60;
break;
case 4:
output.innerHTML = 44;
break;
case 5:
output.innerHTML = 36;
break;
case 6:
output.innerHTML = 26;
break;
default:
output.innerHTML = 133;
}
output.innerHTML = this.value;
}
<div class="slidecontainer">
<input type="range" min="1" max="6" value="1" class="slider" id="myRange">
<p><span id="demo"></span> BC</p>
</div>
Currently it outputs 1 to 6 so it does function and I can set the default value to 133 before input, it just doesn't push out the values I need once the slider is moved.
Is a switch statement the correct tool for this job and, if so, where have I gone wrong?
this.value returns a string. You need to make it return a number in order for your comparison to work. Or compare against strings. Either way, the below example works. Look how I added parseInt(this.value) inside your switch operator.
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = 133;
slider.oninput = function() {
switch (parseInt(this.value)) {
case 1:
output.innerHTML = 133;
break;
case 2:
output.innerHTML = 88;
break;
case 3:
output.innerHTML = 60;
break;
case 4:
output.innerHTML = 44;
break;
case 5:
output.innerHTML = 36;
break;
case 6:
output.innerHTML = 26;
break;
default:
output.innerHTML = 133;
}
}
<div class="slidecontainer">
<input type="range" min="1" max="6" value="1" class="slider" id="myRange">
<p><span id="demo"></span> BC</p>
</div>
I am just thinking out loud, is there a more elegant way for my coding solution. The code is working, but I've build a weather app with Freecodecamp.com and the task was to include a fahrenheit/celsius switch. So, there is an API which gives me the temperature, after I click a button, which gets my position. This temperature is in Fahrenheit. Before the output in html starts, the status of the switch should be checked and the temperature should be given out in Fahrenheit or Celsius. After I click the button again I can switch between Fahrenheit and Celsius Temperature.
In my mind, it was logical. Check the prop with IF (Celsius), else (Fahrenheit). Then after the state of the selector changes, the temperature should change accordingly.
My question is, can this code be optimized, I just started with Javascript and the code quality feels suboptimal. Thanks in advance.
Edit: I don't know why I get down voted, trolls?
Working Prototype HERE
JS:
<script>
function a() {
var apiKey = "40683c3325e6ebb13cbf4331b7cc1f44";
var url = "https://api.darksky.net/forecast/";
var lati;
var longi;
var icon;
var data;
var text;
var tempFahrenheit;
var tempCelsius;
var textSummary;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
$("#out").html("Geolocation is not supported by this browser.");
}
function showPosition(position) {
var lati = position.coords.latitude;
var longi = position.coords.longitude;
$.getJSON(url + apiKey + "/" + lati + "," + longi + "?callback=?", function(data){
//console.log(data);
tempFahrenheit = data.currently.temperature;
textSummary = data.currently.summary;
// Different sayings based on icon API output
var icon = data.currently.icon;
switch(icon){
case "clear-day":
var text = "Cryyyssstaaal clear today. No clouds, not even the cloud service is working.";
var icon = "img/SVG/Sun.svg";
break;
case "clear-night":
var text = "Clear night.";
var icon = "img/SVG/Moon.svg";
break;
case "rain":
var text = "You need a shower? Now is your time. It's raining.";
var icon = "img/SVG/Umbrella.svg";
break;
case "snow":
var text = "It's so cold. I'm farting snowflakes.";
var icon = "img/SVG/Snowflakes.svg";
break;
case "sleet":
var text = "Falling ice cream or snow rain. Don't know";
var icon = "img/SVG/Cloud-Snow-Sun-Alt.svg";
break;
case "wind":
var text = "Flying umbrella ahead. WIND!?!?!?!";
var icon = "img/SVG/Wind.svg";
break;
case "fog":
var text = "Fucking Fog...";
var icon = "img/SVG/Shades.svg";
break;
case "cloudy":
var text = "Cloudy with a chance of ...";
var icon ="img/SVG/Cloud.svg";
break;
case "partly-cloudy-day":
var text = "Cloudy, but only above you. Sorry.";
var icon ="img/SVG/Cloud-Sun.svg";
break;
case "partly-cloudy-night":
var text = "Cloudy. Have you looked out the window today?";
var icon ="img/SVG/Cloud-Moon.svg";
break;
case "hail":
var text = "Be aware Golf balls made of ice are flying around.";
var icon = "img/SVG/Cloud-Hail.svg";
break;
case "thunderstorm":
var text = "Thor angry. Thor making noise.";
var icon = "img/SVG/Cloud-Lightning.svg";
break;
case "tornado":
var text = "That's .... have you seen it? That was your neighbours car. A tornado is close.";
var icon = "img/SVG/Tornado.svg";
break;
default:
var text = "no weather found. pls restart...";
var icon = "img/SVG/Compass.svg";
break;
}
$("#text").html(text);
$("#icon").attr("src",icon);
$("#summary").html(textSummary);
if($("#tempSwitch").prop("checked") == true) {
var tempCelsius = ((tempFahrenheit-32)/1.8).toFixed(2);
$("#temperature").html(tempCelsius);
} else {
$("#temperature").html(tempFahrenheit);
}
$("#tempSwitch").change(function() {
if($("#tempSwitch").prop("checked") == true) {
var tempCelsius = ((tempFahrenheit-32)/1.8).toFixed(2);
$("#temperature").html(tempCelsius);
} else {
$("#temperature").html(tempFahrenheit);
}
});
})
};
};
EDIT: HTML Code
<h1>No Bullshit Weather App</h1>
<p>Click the button to check the weather</p>
<p>Alternative: If you have a window and can move your head, look outside to check the weather</p>
<p><button onclick="a()">Show my location</button></p>
<div id="out"></div>
<div id="temperature"></div>
<input id="tempSwitch" type="checkbox" unchecked data-toggle="toggle" data-on="Celsius" data-off="Fahrenheit">
<div id="text"></div>
<div id="summary"></div>
<img id="icon" src="">
you can do somthing like this? I could not test it because the api didnt seem to work on your github page.
var temp;
function checkTemp()
{
//CELCIUS
if($("#tempSwitch").checked)
{
temp = ((tempFahrenheit-32)/1.8).toFixed(2);
}
//FAHRENHEIT
else
{
temp = tempFahrenheit;
}
//SET HTML
$("#temperature").html(temp);
}
//ONCHANGE RUN FUNCTION CHECKTEMP
$("#tempSwitch").change(checkTemp);
//FIRST TIME RUN FUNCTION
checkTemp();
I don't think is a more elegant way but you can try the ternary operator:
tempFahrenheit = 0;
$("#tempSwitch").change(function() {
var checked = $(this).is(":checked")
var tempCelsius = ((tempFahrenheit-32)/1.8).toFixed(2);
$("#temperature").html(checked?tempCelsius:tempFahrenheit);
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="tempSwitch" type="checkbox" unchecked data-toggle="toggle" data-on="Celsius" data-off="Fahrenheit">
<div id="temperature"></div>
I have got a simple switch case example in javascript. Though, the value in paragraph should be reflected as the third option in switch-case, it is showing nothing or blank paragraph. Pl, help!
<html>
<head></head>
<body>
<p id="para1"></p>
<script>
var i = 3;
switch(i){
case 1: {
document.getElementById('para1').value = "The value is one.";
break;
}
case 2: {
document.getElementById('para1').value = "The value is two.";
break;
}
case 3: {
document.getElementById('para1').value = "The value is three.";
break;
}
default:{
document.getElementById('para1').value = "The value is undefined."
}
}
</script>
</body>
</html>
p tag in not input element hence it doesn't have value. You should use innerHTML to set the value.
<html>
<head></head>
<body>
<p id="para1"></p>
<script>
var i = 3;
switch(i){
case 1: {
document.getElementById('para1').innerHTML = "The value is one.";
break;
}
case 2: {
document.getElementById('para1').innerHTML = "The value is two.";
break;
}
case 3: {
document.getElementById('para1').innerHTML = "The value is three.";
break;
}
default:{
document.getElementById('para1').innerHTML = "The value is undefined."
}
}
</script>
</body>
</html>
Use innerHTML instead of value:
<html>
<head></head>
<body>
<p id="para1"></p>
<script>
var i = 3;
switch(i){
case 1: {
document.getElementById('para1').innerHTML = "The value is one.";
break;
}
case 2: {
document.getElementById('para1').innerHTML = "The value is two.";
break;
}
case 3: {
document.getElementById('para1').innerHTML = "The value is three.";
break;
}
default:{
document.getElementById('para1').innerHTML = "The value is undefined."
}
}
</script>
</body>
</html>
var i = 3;
switch(i){
case 1: {
document.getElementById('para1').innerHTML = "The value is one.";
break;
}
case 2: {
document.getElementById('para1').innerHTML = "The value is two.";
break;
}
case 3: {
document.getElementById('para1').innerHTML = "The value is three.";
break;
}
default:{
document.getElementById('para1').innerHTML = "The value is undefined."
}
}
<p id="para1">test</p>
My task is checking what an user keys in. If he keys in "Mars", he gets the value.
PLanet: <input type="text" id="form_1">
<input type="submit" onClick="send()" value="Send">
<script>
var planetEntered = document.getElementById('form_1').value;
var plantesLength = new Array(3);
plantesLength['Mars'] = 52;
plantesLength['Venera'] = 30;
plantesLength['Earth'] = 10;
plantesLength['Merkyriy'] = 60;
alert(plantesLength['Merkyriy']);
function send() {
switch(form_1) {
case 'Mars':
alert(plantesLength['Mars']);
break;
case 'Venera':
alert(plantesLength['Venera']);
break;
case 'Earth':
alert(plantesLength['Earth']);
break;
case 'Merkyriy':
alert(plantesLength['Merkyriy']);
break;
default:
alert("К сожалению, мы не нашли ни одну программу.");
break;
}
}
The function returns default-block. How to fix? Thanks.
try this
you have to get the input values inside the send function.
Demo Link http://jsbin.com/ejaSUTiH/1/
PLanet: <input type="text" id="form_1">
<input type="submit" onClick="send()" value="Send">
<script>
var plantesLength = new Array(3);
plantesLength['Mars'] = 52;
plantesLength['Venera'] = 30;
plantesLength['Earth'] = 10;
plantesLength['Merkyriy'] = 60;
alert(plantesLength['Merkyriy']);
function send() {
var planetEntered = document.getElementById('form_1').value;
console.log(planetEntered);
switch(planetEntered) {
case 'Mars':
alert(plantesLength['Mars']);
break;
case 'Venera':
alert(plantesLength['Venera']);
break;
case 'Earth':
alert(plantesLength['Earth']);
break;
case 'Merkyriy':
alert(plantesLength['Merkyriy']);
break;
default:
alert("К сожалению, мы не нашли ни одну программу.");
break;
}
}
</script>
You've to declare a variable inside the function send(): And set
planetEntered in switch case for checking:
function send() {
var planetEntered = document.getElementById('form_1').value; // Here
switch(planetEntered) { // Change
}
}
JS Fiddle Demo
You don't assign the value of the input box in the send() method so it's value is the default (empty) when send() is called.