Change h1 using javascript switch statement based on input - javascript

I need to know how to get the h1 sun emoji to change when user input less than or equal to 0.
I feel like I have the logic but just need to code.
Once the user inputs a temperature less than 0 the h1 needs to change to a certain emoji or content.
Can I get some advice please. I am struggling here. this is my code:
function question() {
let city = prompt("what city do you live in?");
let temp = prompt("What temperature is it?");
let h1 = document.queryselector("h1");
h1.innerHtml = "Currently" + temp + "degrees" + " in " + city;
}
function change() {
switch (true) {
case (temp <= 0):
document.getElementById("h1").innerHtml = "Currently" + temp + "degrees" + "in " + city;
}
}
<h1>
sun emoji
</h1>
<h1 class="temperature">
Currently 21 degrees in Tokyo
</h1>
<h2>
13 degrees / <strong>23 degrees</strong>
</h2>
The h1 has to change to a different emoji based on the users response of less than or equal to 0.
Along with the emoji I need to input of the user city to change along with it.I just need the h1 section to change.Should I use a switch or if else statement?

Firstly, you have multiple h1 elements - queryselector only returns the first one, so in this case you would be replacing the emoji, not the text.
It would be prudent to give the various elements that you intend to edit id fields.
<h1 id="emoji-el">
sun emoji
</h1>
<h1 id="temp-details" class="temperature">
Currently 21 degrees in Tokyo
</h1>
Now you can use queryselector to select the correct elements.
Secondly, I'd like to say that it is good practice to have every function have a single responsibility - for example, one function get a correct emoji, while another puts things into elements.
Given this, I would use an if list because of the way your condition is structured:
function getEmoji(temp) {
if (temp < 0) return ❄️;
if (temp < 13) return ☁;
return ☀️;
}
You can likely use emojis directly for HTML text values, and if you only use upper limits like I did you don't need elses. IMO this is the nicest way.
You final function would look something like this:
function questionUser() {
const city = prompt("What city do you live in?");
const temp = prompt("What temperature is it?");
updatePage(temp, city);
}
function updatePage(temp, city) {
const emojiElement = document.queryselector("#emoji-el");
const tempElement = document.queryselector("#temp-details");
const emoji = getEmoji(Number(temp));
emojiElement.innerHtml = emoji;
tempElement.innerHtml = `Currently ${temp} degrees in ${city}.`;
}
This way you would be able to re-use the update logic elsewhere, and also it is clear what every function does.
Hope this helps.

Can achieve the same result with switch or if statement.
You just have to trigger the function on onChange or onBlur.

It's advisable to use classNames or id's for your html element, which makes retrieving specific elements easier.
Switch is suitable if your conditions have a fixed value. In this case a a ternary (conditional operator) would be an idea.
Here's an exemplary snippet demoing ternary or switch to determine the 'emoji' to display, based on the given temperature. It uses event delegation for handling the button click.
document.addEventListener(`click`, handle);
function handle(evt) {
// act only if button#showTemperatures is clicked
if (evt.target.id === `showTemperatures`) {
return question();
}
}
function emo(temp) {
const emojiTxt = temp < 15 ? `*Brr**` :
temp < 25 ? `*nice*` :
temp < 30 ? `*it's getting hot here*` : `*tropical!*`;
document.querySelector(`.emoji`).textContent = emojiTxt;
}
/* using switch is possible, but you need something extra */
function emoSwitch(temp) {
const lt = n => temp < n;
let emojiTxt = ``;
switch (true) {
case lt(10):
emojiTxt = `*Brr*`;
break;
case lt(25):
emojiTxt = `*nice*`;
break;
case lt(30):
emojiTxt = `*it's getting hot here*`;
break;
default:
emojiTxt = `*tropical!*`;
}
document.querySelector(`.emoji`).textContent = emojiTxt;
}
function question() {
// id's make your coding life simple
const city = document.querySelector(`#city`).value;
const temp = document.querySelector(`#temp`).value;
// one of the values is not filled, alert
if (!city.trim() || temp < 0) {
return alert(`please fill out both fields`);
}
// fill in h1.temperature
document.querySelector(`.temperature`).textContent =
`Currently ${temp} degrees in ${city}`;
// fill in the emoji
return document.querySelector(`#switch`).checked ?
emoSwitch(temp) : emo(temp);
}
<!-- changed for demo -->
<p>
<b class="emoji"></b>
<b class="temperature">Currently 21 degrees in Tokyo</b>
</p>
<hr>
<p><input type="text" id="city"> What city do you live in?</p>
<p><input type="number" id="temp" min="0" max="55"> What temperature is it up there?</p>
<p>
<button id="showTemperatures">Fill in</button>
<input type="checkbox" id="switch">Use switch
</p>

Related

How to make a text appear with a desired innerHTML using javascript/jquery

There is a button and a h2 tag. the h2 tag has its visibilty=hidden.
When the button is clicked, I want to call a function that calculates the cost and changes the innerHTML of h2 accordingly and then changes its visibility=visible.
HTML:
<main class="form-signin">
<form>
<div class="card">
<label for="inputAdult">Enter number of adults</label><input type="number" id="inputAdult" class="form-control" placeholder="No. of adults" required>
<label for="inputChildren">Enter number of children (4-12yo)</label><input type="number" id="inputChildren" class="form-control" placeholder="No. of children" required>
<button type="button" onclick="showCost()" id="btn3">Calculate my cost</button>
<h2 class="changeCost">Your total cost: $0</h2>
</div>
</form>
</main>
JavaScript / jQuery :
$("h2").css("visibility","hidden");
function calculateCost(){
var a = $("#inputAdult").val();
var c = $("#inputchildren").val();
if (((a+c)%3==0)||((a+c)%3==1)) {
var rooms = (a+c)/3;
}
else {
var rooms = ((a+c)/3)+1;
}
var cost = rooms*300;
return cost;
}
function showCost() {
var display = "Your total cost is: $" + calculateCost();
var x = $("h2");
x.value = display;
$("h2").css("visibility","visible");
}
Try x.text(display) instead of setting value. That changes the innerText of the element. If you'd like to set its HTML content, use x.html(display).
The value accessor is used for plain HTMLElement objects, not for jQuery-wrapped objects.
Apart from this, you should never access a tag solely by its tag name. Always give it some kind of class name or ID. You already gave it the changeCost class, so you could do $("h2.changeCost") rather than $("h2").
To avoid getting NaN do the following:
Javascript is case sensitive so replace line
var c = $("#inputchildren").val();
with
var c = $("#inputChildren").val();
I would also consider declaring rooms variable from if and else scope so it is accessible on calculations: see full function bellow:
function calculateCost(){
var a = $("#inputAdult").val();
var c = $("#inputChildren").val();
var rooms = 0;
if (((a+c)%3==0)||((a+c)%3==1)) {
rooms = (a+c)/3;
}
else {
rooms = ((a+c)/3)+1;
}
var cost = rooms*300;
return cost;
}

How do I get a HTML div element to loop using javascript?

I have a block of code, a quiz creation template, and i need the block of code for the question and possible answers to be looped, for however many times the user asks for. I have been trying for hours and im really not sure whats wrong.
<div id="questionform" class="modal">
I already have the amount of questions the user would like under this line of code.
var amount = prompt("Please enter the amount of questions you would like", "<amount goes here>");
below is the javascript i am using to try and loop the writing within the div.
var i;
var amount;
var contents = document.getElementById("questionform").innerHTML;
for (i = 1; i=amount; i++) {
a.document.write(contents);
}
Your condition in your for-loop is wrong. You have an assignment instead of an evaluation.
for (i = 1; i=amount; i++)
You should be creating elements and appending them to the DOM. Avoid using document.write. Also, please begin indexing at zero, unless you need to start at 1.
Update
If you provide a name attribute to your input fields, they will be submitted with the form on submit.
input.setAttribute('name', 'answer[]');
When you hit submit, the input field values will be sent to the server as:
answer=foo&answer=bar
or:
{ "answer" : [ "foo", "bar" ] }
Refer to this if you are still confused: POST an array from an HTML form without javascript
Example
let amount = prompt("Please enter the amount of questions you would like", 5);
let questionForm = document.getElementById("question-form");
let answerList = questionForm.querySelector(".answer-list");
for (let i = 0; i < amount; i++) {
let inputWrapper = document.createElement('DIV');
let label = document.createElement('LABEL');
let input = document.createElement('INPUT');
input.setAttribute('type', 'text');
input.setAttribute('name', 'answer[]');
label.textContent = 'Answer ' + String.fromCharCode(i + 65) + ': ';
inputWrapper.classList.add('input-wrapper');
inputWrapper.appendChild(label);
inputWrapper.appendChild(input);
answerList.appendChild(inputWrapper);
}
.input-wrapper {
margin-bottom: 0.25em;
}
.input-wrapper label {
display: inline-block;
width: 5em;
font-weight: bold;
}
<form id="question-form" class="modal">
<div class="answer-list"></div>
<button type="submit">Submit</button>
</form>

Replace previously generated content in Javascript based on user input

I have a button on that perfroms the collatz conjecture with the push of a button, and takes in the user's input. It then prints out the steps as a list into a p tag. I wanted to know how I would override the previously created steps, as I have noticed calling the method again adds to the end of the previous list.
The main reason I'm using a list is for readability, so I don't want to get rid of it unless there's a better way of doing this.
//collatz function
function collatz (){
var step = 0;
var inputCollatz = prompt("What number do you want to add?")
if (inputCollatz <= 1){
document.getElementById("collatz").innerHTML = "No steps required, already less than or equal to 1.";
}
else if(isNaN(inputCollatz)){
document.getElementById("collatz").innerHTML = "Please add a number.";
}
else if (inputCollatz.toString().indexOf('.') != -1){
document.getElementById("collatz").innerHTML = "Whole numbers please!";
}
else{
while(inputCollatz > 1){
//needed help w/ ternary operators, still need practice with it
inputCollatz = inputCollatz % 2 ? 3 * inputCollatz + 1 : inputCollatz / 2;
step++;
var item = document.createElement("li");
var text = document.createTextNode(inputCollatz);
item.appendChild(text);
var list = document.getElementById("collatz");
list.appendChild(item);
}
document.getElementById("steps").innerHTML = "Number of steps: " + step.toString();
}
}
This is the button in html.
<button onclick="collatz()">Find the number of steps.</button><br/>
<br/>
<div id="collatz"></div>
<br/>
<div id="steps"></div>
I was suggested to clear out the collatz div before each loop, which worked.
...
else {
document.getElementById("collatz").innerHTML = '';
while(inputCollatz > 1) {
....

Currency converter doesn't work within a defined limit

I created a Bitcoin (BTC) to Canadian Dollar (CAD) converter that uses the current price from a different site, now I am trying to limit the values acceptable for the BTC/CAD inputs but it doesn't work.
The limits I want to set is $2 to $99.99 for CAD and the BTC equivalent for max/min but it doesn't want to work...
Fiddle:
https://jsfiddle.net/z735tswj/ all the relevant code is in the html tab or below
<input id="btcc" type="text" onkeyup="btcConvert()" onchange="btcCheck()">BTC</input>
<input id="cadc" type="text" onkeyup="cadConvert()" onchange="cadCheck()">CAD</input>
<br>
<br>
<script>
function btcConvert() {
var btc = document.getElementById("btcc").value;
var btcCalc = btc * price;
var btcCalc = btcCalc.toFixed(2);
document.getElementById("cadc").value = btcCalc;
btcCheck();
}
function cadConvert() {
var cad = document.getElementById("cadc").value;
var cadCalc = cad / price;
var cadCalc = cadCalc.toFixed(8);
document.getElementById("btcc").value = cadCalc;
cadCheck();
}
function btcCheck() {
if (btc.value < 0.001649) btc.value = 0.001649;
if (btc.value > 0.082259) btc.value = 0.082259;
btcConvert();
}
function cadCheck() {
if (cad.value < 2) cad.value = 2;
if (cad.value >= 100) cad.value = 99.99;
cadConvert();
}
</script>
Got it working, your script was not passing the input value to cadCheck()
I just made a few edits to get it to work. cadCheck() will get the value of the input before running cadConvert().
function cadCheck(input) {
if (input.value < 2) input.value = 2;
if (input.value >= 100) input.value = 99.99;
cadConvert();
}
I also took out the onkeyup="cadConvert() because you are calling that in cadCheck() and added this("this" being the input's value) to onchange="cadCheck().
new html <input id="cadc" type="text" onchange="cadCheck(this)">CAD</input>
Here is my code https://jsfiddle.net/so7s9efr/
Don't mean to be the "just use this" guy, but currency conversion is a common, solved problem and there are many good solutions out there.
A good one is money.js
Was working on a fiddle solution, but Paul Allen's works fine.

Adding to variable value on condition in Javascript

I have a variable called "total" that I would like to assign a number (or price) to and then add to that number when certain options are selected or checked. Here is the code I have so far.
Here is the code that sets the initial value (base price) of the variable that will be added to. THIS CODE CURRENTLY WORKS.
$('input[name=trimlevel]').change(function(){
var total = 0;
if(document.getElementById('basetrim').checked==true) {
var total = 0;
var basetrim = 3550.00;
total = total + basetrim;
$('#myTotal').html('$' + total);
}else if(document.getElementById('upgrade').checked==true) {
var total = 0;
var upgrade = 2400.00;
total = total + upgrade;
$('#myTotal').html('$' + total);
}else {
$('#myTotal').html('$' + total);
}
});
Here is an example of the code used to "add to" the value of the variable. THIS IS NOT WORKING.
$('input[name=leather]').change(function(){
if(document.getElementById('leather).checked == true) {
var leather = 180.00;
total = total + leather;
$('#myTotal').html('$' + total);
}
});
Here is the HTML for reference
<div class="modelsel">
<h2>1. SELECT MODEL</h2> <br>
<label for="basetrim">BASE MODEL</label>
<input id="basetrim" type="radio" name="trimlevel" value="2400.00">
<label for="upgrade">UPGRADED MODEL</label>
<input id="upgrade" type="radio" name="trimlevel" value="3550.00">
</div>
<div class="inside">
<h2>3. BASE MODEL ADD-ONS</h2><br>
<input type="checkbox" value="180.00" id="leather" name="leather" />
<label for="leather">Leather Seat (+ $180.00)</label><br>
</div>
<div id="myTotal"></div>
I am relatively new to Javascript and have been struggling with this for hours. Any help is appreciated. Thanks in advance.
Only some modifications need to be made in order to get things to work:
First one, there's a typo here:
if(document.getElementById('leather).checked == true) {
You missed a ' so substitute it by:
if(document.getElementById('leather').checked == true) {
Second, define the var total out of the functions and make it available to all of them. If you have your methods in the ready function you can define total there. Also remove the definition of total inside the functions or you won't use the one who is defined in ready.
Third, when the user clicks the checkbox, you're always adding value (don't know if that's what you want). In this fiddle, I add or diminish the amount of total according to the state of the checkbox.
The solution is already in the comments. The context of the functions is different. You can either define total outside of the functions or use an object for your behavior.
var someObject = {};
inside your function you can write with the dot notation.
someObject.total = 10;
$('input[name=trimlevel]').change(function(){
var total = 0;
if($(this).checked==true)) {
total = total + $(this).val();
}
$('#myTotal').html('$' + total);
});
Consider writing a comprehensive named function which adds up everything that can possibly contribute to your total :
function calculate() {
var total = 0;
if(document.getElementById('basetrim').checked) {
total = total + 3550.00;
} else if(document.getElementById('upgrade').checked) {
total = total + 2400.00;
}
if(document.getElementById('leather').checked) {
total = total + 180.00;
}
// further additions here
// further additions here
// further additions here
$('#myTotal').html('$' + total);
});
Then attach that named function as the event handler wherever necessary :
$('input[name=trimlevel]').change(calculate);
$('input[name=leather]').change(calculate);
//further attachments of calculate as event handler here
//further attachments of calculate as event handler here
//further attachments of calculate as event handler here

Categories