I want to build code which convert Temp from Celcius to Fahrenheit by using any Function in Java Script
I am wondering how to take the value from window.prompt and use it for further converting temperature by any functions in JavaScript?
I Created HTML and now in JavaScript I wrote window.prompt where i can put the value. But I can't figure out how to take this value from window.prompt and convert it to Fahrenheit by using function.
var button = document.getElementById('greeter-button');
button.addEventListener('click', function() {
Temperature = window.prompt('What is temperature in celcius?');
});
<div id="button_and_text">
<button id="greeter-button">Button!</button>
<br> Click the button! Check the temperature!
<br><br>
</div>
<div id="greeter-output"></div>
You mean this?
Note you would normally need to convert the string returned from the prompt to a number, for example by using +temperature, but the multiplication casts the string to a number for you. Also the operator precedence helps here
window.addEventListener("load", function() { // on page load
var button = document.getElementById('greeter-button'),
output = document.getElementById('greeter-output');
button.addEventListener('click', function() {
var temperature = window.prompt('What is temperature in celcius?');
if (temperature != null) {
output.innerHTML = temperature + "°F = " +
(temperature * 9 / 5 + 32) + "°C";
}
});
});
<div id="button_and_text">
<button id="greeter-button">Button!</button><br/>
Click the button! Check the temperature!
</div>
<div id="greeter-output"></div>
The conversion formula is more important and once you get that then convert it to number and use innerHTML
let button = document.getElementById('greeter-button');
button.addEventListener('click', function() {
let temp = +window.prompt('What is temperature in celcius?');
let f = ((9 * temp) / 5) + 32;
document.getElementById('greeter-output').innerHTML = f
});
<div id="button_and_text">
<button id="greeter-button">Button!</button>
<br> Click the button! Check the temperature!
<br><br>
</div>
<div id="greeter-output"></div>
Related
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>
So i have this code:
<div class="wrapper">
<p id="ex"></p>
<script>
function celMessager() {
var celMs = window.prompt("Enter the celsius grades:");
celMs = parseFloat(celMs);
if (celMs == null) {
document.getElementById("ex").innerHTML = "Error.";
}
else {
document.getElementById("ex").innerHTML = celConversor();
}
}
</script>
<button class="button" type="button" onclick="
celMessager();
">
Conversor Celsius.
</button>
</div>
And i want to store the value of the user input (celMs) into the only parameter that celConversor() takes:
function celConversor(celGrades) {
fahGrades = (celGrades * 9/5) + 32;
return fahGrades;
}
So the number that the user enters, become the celsius grades that are going to change into fahrenheit and show it as a paragraph.
How can I do this? tried making the celGrades variable = to celMs and celMs to celGrades, but it always returns "NaN" in the paragraph, even after i added the "parseFloat" line.
You're getting this error celConversor requires a parameter, but you're not passing any parameters to it. Change this line:
document.getElementById("ex").innerHTML = celConversor();
to this:
document.getElementById("ex").innerHTML = celConversor(celMs);
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.
<form>
<input type="text" name="" value="">
</form>
//for loop used to calculate balance after payment(x) and interest
// the variable I want defined from the form input box
for(i = 6000; i>=10; i = i * (1+0.2/26)-x){
var x = 155;
document.write("Balance " + " $" + i + "<br/><br/>");
}
You could attach a pseudo class in your input element and then get the value inserted like below:
<input type="text" name="" value="" class="js-interest">
<script>
var ele = document.getElementsByClassName("js-interest")[0];
var value = parseFloat(ele.value);
</script>
You can try document.getElementById('input_id').value and then use parseInt to get it as an integer, as below:
var x = parseFloat(document.getElementsByName('number_box').value);
Also, the html must look something like this:
<form>
<input type="text" name="number_box" value="">
</form>
Optionally, instead of document.getElementsByName() you can use document.getElementById() or document.getElementsByClassName().
Update:
If I am not wrong
for(i = 6000; i>=10; i = i * (1+0.2/26)-x){
var x = 155;
document.write("Balance " + " $" + i + "<br/><br/>");
}
It seems like you are writing to the DOM inside a for loop don't do that calculate your ANS and then write to the DOM.
Also, don't read the data from input inside the loop. (You will be repeatedly reading and writing the data thats not good.)
Your for loop for(i = 6000; i>=10; i = i * (1+0.2/26)-x) is incrementing using some expression i = i * (1+0.2/26)-x (make sure it is bound to the condition and its not making the loop infinite)
You can select the value from the input field using the following code
x = parseInt(document.querySelector('form input[name="my_number"]').value);
document.querySelector it uses CSS style selector. So, to select the input field inside your form. I have added a name to the form as name="my_number"
<input type="text" name="my_number" value="">
now using the css selector form input[name="my_number"] it select the input field inside a form with name "my_number"
The whole Query selector that will return the input element is this,
document.querySelector('form input[name="my_number"]')
now to get the value of the input field you have to read the value property of the input field.
document.querySelector('form input[name="my_number"]').value
This will return your input value as string.
Now, we need to parse that string value to a Integer format.
We do that like this, (using parseInt)
parseInt(document.querySelector('form input[name="my_number"]').value)
I have added you code in a function named calc
function calc() {
var x = parseInt(document.querySelector('form input[name="my_number"]').value);
var ans= calculate_your_value(x);
document.write("Balance " + " $" + ans + "<br/><br/>");
}
I have fetched the answer from a function named get calculated answer and its good to do this way.
function calculate_your_value(x){
// calculate the ans the for loop seems buggy
//for (i = 6000; i >= 10; i = i * (1 + 0.2 / 26) - x) {}
return x; //dummy ans
}
It is called when you submit the form.
To do that I have added onsubmit='calc()' on your form tag.
<form onsubmit='calc()'>
Additionally, I have added this function that submits the form when you have pressed enter too (Just for fun) :)
document.onkeydown=function(){
if(window.event.keyCode=='13'){
calc();
}
}
It just listens for key down press and check if it is a enter key (keycode is 13)
and calls the same calc function.
function calc() {
var x = parseInt(document.querySelector('form input[name="my_number"]').value);
var ans= calculate_your_value(x);
document.write("Balance " + " $" + ans + "<br/><br/>");
}
document.onkeydown = function() {
if (window.event.keyCode == '13') {
calc();
}
}
function calculate_your_value(x){
// calculate the ans the for loop seems buggy
//for (i = 6000; i >= 10; i = i * (1 + 0.2 / 26) - x) {}
return x; //dummy ans
}
<form onsubmit='calc()'>
<input type="text" name="my_number" value="">
<input type="submit" id="submitbtn" />
</form>
Hi I wrote something JQ but i'm not sure is correct :) so would like you to help me figure out how
1.When the user clicks the button (Show results)
2.the two figures are added together and the result is displayed in the span # result
3.check on user input, as a warning, if there is no number entered into the text boxes
only pure jQuery please :)
Thank you in advance for your help.
http://jsfiddle.net/4ke8k5vp/
<body>
<div id="wrapper">
<p>
<input type="text" id="num1" placeholder="Enter a number" value="" />
+
<input type="text" id="num2" placeholder="Enter a number more" value="" />
=
<span class="alert" id="result"></span>
</p>
<input type="button" value="Show results" />
</div>
$(document).ready(function () {
var num1 = $('#num1');
var num2 = $('#num2');
var total = num1 + num2;
$(":button").click(function () {
$("span").html();
});
});
$(document).ready(function () {
var num1 = $('#num1');
var num2 = $('#num2');
$(":button").click(function () {
// Update the total each time the button is clicked.
// Use `parseInt` to convert the string to an integer. Add them.
var total = parseInt(num1.val(), 10) + parseInt(num2.val(), 10);
// Pass the total to the html
$("span").html(total);
});
});
There are a couple of other things you could do to optimize your code, such as adding IDs to the button and the span, but that's outside of your question.
In you javascript you need to cast $('#num1') and $('#num2') to int or float with parseInt() or parseFloat() before adding them.
Also, in your html, the input type should be number, not text.
The whole javascript funtion should be more like this
$(":button").click(function () {
var num1 = $('#num1').val();
var num2 = $('#num2').val();
if (num1 == "" or num2 == "") alert("Please fill both inputs");
else {
var total = parseInt(num1) + parseInt(num2);
$("span").text(total);
}
}
Here is a fiddle: http://jsfiddle.net/Lon5wp7t/
I broke this down for you so you could hopefully learn from the code! The end of this post will give you what you want, but I've gone through to illustrate how we get to that point!
$(document).ready(function () {
// do whatever
});
The above part of the code tells the computer to work what's between the brackets when the document is loaded
$(":button").click(function () {
// do whatever
});
The above adds what's called an "Event Listener" to anything labeled as a button, when that event is triggered it works whatever is between the brackets. In this case it is the "click" event.
You were correct on putting these two together, like so:
$(document).ready(function () {
$(":button").click(function () {
// do whatever
});
});
So what we have so far is that, when the document is loaded, the script adds an event listener to anything labeled button. It doesn't do anything(you'll notice the "//do whatever" is just a comment) but we can certainly fix that.
On click we want the values to be pulled from the input boxes.
$(document).ready(function () {
$(":button").click(function () {
var num1 = $('#num1').val();
var num2 = $('#num2').val();
});
});
Great! Now when the button is clicked, it pulls the input and puts it into 2 variables, num1 and num2. However, when you pull the input you have to realize that what you are pulling from the input boxes are STRINGS. Strings are not recognized as being able to be added. If num1 was equal to 2 and num2 was equal to 3, when you added them together instead of "5" you would get "23". They are concatenated and not computed for a sum. To change that we have to change the input from STRINGS to INTEGERS. We can do this by using the function parseInt() - which will read a string and return an integer.
$(document).ready(function () {
$(":button").click(function () {
var num1 = $('#num1').val();
var num2 = $('#num2').val();
var total = parseInt(num1) + parseInt(num2);
});
});
Finally we have a total, all we have left to do is put it into the span tag!
$(document).ready(function () {
$(":button").click(function () {
var num1 = $('#num1').val();
var num2 = $('#num2').val();
var total = parseInt(num1) + parseInt(num2);
$("span").html(total);
});
});