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);
Related
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;
}
I've added ids and data operators and numbers to the html but the output still shows "NaN on the screen
I've tried to test it in the suite but the following tests don't pass:
My calculator should contain 10 clickable elements containing one number each from 0-9, with the following corresponding IDs: id="zero", id="one", id="two", id="three", id="four", id="five", id="six", id="seven", id="eight", and id="nine".
My calculator should contain 4 clickable elements each containing one of the 4 primary mathematical operators with the following corresponding IDs: id="add", id="subtract", id="multiply", id="divide".
My calculator should contain a clickable element with an id="clear"
At any time, pressing the clear button clears the input and output values, and returns the calculator to its initialized state; 0 should be shown in the element with the id of "display"
5.At any time, pressing the clear button clears the input and output values, and returns the calculator to its initialized state; 0 should be shown in the element with the id of "display"
In any order, I should be able to add, subtract, multiply and divide a chain of numbers of any length, and when I hit "=", the correct result should be shown in the element with the id of "display"
In any order, I should be able to add, subtract, multiply and divide a chain of numbers of any length, and when I hit "=", the correct result should be shown in the element with the id of "display"
I should be able to perform any operation (+, -, *, /) on numbers containing decimal points
I should be able to perform any operation (+, -, *, /) on numbers containing decimal points
I'm guessing I have to use a switch statement somewhere?
Can anyone help me? Thank you.
function getHistory() {
return document.getElementById('previous-operand').innerText;
}
function printHistory(num) {
document.getElementById('previous-operand').innerText = num;
}
function getOutput() {
return document.getElementById('display').innerText;
}
function printOutput(num) {
if (num == "") {
document.getElementById('display').innerText = num;
} else {
document.getElementById('display').innerText = getFormattedNumber(num);
}
}
function getFormattedNumber(num) {
if (num == "minus") {
return "";
}
var n = Number(num);
var value = n.toLocaleString("en");
return value;
}
function reverseNumberFormat(num) {
return Number(num.replace(/,/g, ''));
}
var operator = document.getElementsByClassName("operator");
for (var i = 0; i < operator.length; i++) {
operator[i].addEventListener('click', function() {
if (this.id == "clear") {
printHistory("");
printOutput("");
} else if (this.id == "backspace") {
var output = reverseNumberFormat(getOutput()).toString();
if (output) { //if output has a value
output = output.substr(0, output.length - 1);
printOutput(output);
}
} else {
var output = getOutput();
var history = getHistory();
if (output == "" && history != "") {
if (isNaN(history[history.length - 1])) {
history = history.substr(0, history.length - 1);
}
}
if (output != "" || history != "") {
output = output == "" ?
output : reverseNumberFormat(output);
history = history + output;
if (this.id == "=") {
var result = eval(history);
printOutput(result);
printHistory("");
} else {
history = history.this.id;
printHistory(history);
printOutput("");
}
}
}
});
}
var number = document.getElementsByClassName("number");
for (var i = 0; i < number.length; i++) {
number[i].addEventListener('click', function() {
//get output commas removed
var output = reverseNumberFormat(getOutput());
//
if (output != NaN) { //if output is a number
output = output + this.id;
printOutput(output);
}
});
}
<div id="calculator-grid" class="calculator-grid">
<div class="output">
<div id="previous-operand"></div>
<div id="display"></div>
</div>
<button data-operator="clear" class="operator">AC</button>
<button data-operator="del" class="operator">DEL</button>
<button data-operator="divide" id="divide" class="operator">÷</button>
<button data-number="1" id="one" class="number">1</button>
<button data-number="2" id="two" class="number">2</button>
<button data-number="3" id="three" class="number">3</button>
<button data-operator="multiply" class="operator">*</button>
<button data-number="4" id="four" class="number">4</button>
<button data-number="5" id="five " class="number">5</button>
<button data-number="6" id="six" class="number">6</button>
<button data-operator="add" id="add" class="operator">+</button>
<button data-number="7" id="seven" class="number">7</button>
<button data-number="8" id="eight" class="number">8</button>
<button data-number="9" id="nine" class="nine">9</button>
<button data-operator="minus" id="subtract" class="operator">-</button>
<button data-operator="decimal" id="decimal" class="operator">.</button>
<button data-number="0" id="zero" class="number">0</button>
<button data-operator="equals" id="equals" class="span-two operator">=</button>
</div>
I've made a Codepen to demonstrate your app with minimal styling, I recommend you do this the next time you're asking for help.
https://codepen.io/bashuatdiff/pen/JjoQZoe
I believe the "NaN" value is returned by this function.
function getFormattedNumber(num) {
if (num == "minus") {
return "";
}
var n = Number(num);
var value = n.toLocaleString("en");
return value;
}
The problem is that you're passing in a string to this function - that is, the id value of the Number Button that was clicked, appended to the current Output value. Then you use Number(num) to coerce this string to a number.
Any time you try to create a Number from a string with non-digit characters, the result will be NaN. In this case your id values are "one", "two", etc, none of which can be coerced to a Number - you'll end up with NaN.
Possible solutions:
Don't use word values for your id attributes. Instead of "two", use "2". More generally, you're converting back and forth between strings and numbers a lot throughout this code, and it will help to be aware of when you're expecting a string and when you're expecting a number.
Convert the id attribute to a number before concatenating it to the output. It's important to understand when the Plus symbol (+) is concatenating and when it's adding.
Add checks for "NaN" throughout your code. You had one: output != NaN but this won't actually work. Even NaN isn't equal to NaN. Instead, try something like typeof output == "number".
Good luck.
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>
There are a few ways this can be asked, I'm trying to go with the easiest. Basically, I have two fields... one is to add a number, the other is to subtract. What I want, is when a number is input into either (let's just stick with the add input for now) and have it update at the bottom once the button "+" is pressed. I want that result to stay at the bottom, so when a new value is put into the add box and the button is pressed, it ADDS to the previous total. For the life of me, I can't figure this one out. Once resolved, I'll take care of the subtraction on my own, just need a push in the right direction. The current code is as follows.
<div id="entire">
<div id="content">
<input type="number" id="addInput" placeholder="0">
<button type="button" id="addBtn" onclick="add()">+</button>
<br>
<br>
<input type="number" id="subInput" placeholder="0">
<button type="button" id="subBtn" onclick="sub()">-</button>
<br>
<br>
<div id="totalAmt"></div>
<br>
<input type="button" id="clear" onclick="clearFields()" value="Clear">
<input type="button" id="reset" onclick="reset()" value="Reset">
</div>
</div>
function add() {
var addInput = document.getElementById("addInput").value;
var emptyValue = "";
var total = emptyValue + addInput;
document.getElementById("totalAmt").innerHTML = total;
}
function clearFields() {
document.getElementById("addInput").value = "";
document.getElementById("subInput").value = "";
}
function reset() {
document.getElementById("totalAmt").innerHTML = "";
}
A link to my codepen is below:
http://codepen.io/0ktane/pen/NNdbOq
Your problem is these two lines
var emptyValue = "";
var total = emptyValue + addInput;
when you are concatenating to a string, you get a string back.
Also, you are not even considering the previous value at first place.
Try this, updated pen
function add() {
var addInput = parseInt(document.getElementById("addInput").value); //parse the value to an integer first
var totalAmt = parseInt(document.getElementById("totalAmt").innerHTML); //parse the value to an integer first
totalAmt = isNaN(totalAmt) ? 0 : totalAmt; //if the value is NaN(not a number) reset it to 0
addInput = isNaN(addInput) ? 0 : addInput;//if the value is NaN(not a number) reset it to 0
document.getElementById("totalAmt").innerHTML = totalAmt + addInput ; //output the correct value
}
var total = 0;
function add() {
var addInput = parseInt(document.getElementById("addInput").value);
total = total + addInput;
document.getElementById("totalAmt").innerHTML = total;
}
Please check out the code below. I want to get the value entered in the prompt box into function dis(). How can I do that?
<!DOCTYPE html>
<html>
<head>
<script>
function display()
{
var z=prompt("enter your name...");
if(z!=null)
{
document.getElementById("demo").innerHTML="thankyou"+z+"..";
document.getElementById("case").style.display='block';
}
else
document.getElementById("demo").innerHTML="thankyou";
}
function dis()
{
var a=document.getElementById("aaa").value;
alert("your mark is"+a);
}
</script>
</head>
<body>
<p id="demo">click on the button.....</p>
<button type="button" onclick="display()">submit</button>
<div id="case" style="display:none">
<input type="text" id="aaa" name="myText" onDblClick="dis()">enter your mark
</div>
</body>
</html>
If you want to directly pass value to dis() function then change your script to
function display() {
var z = prompt("enter your name...");
if (z != null) {
document.getElementById("demo").innerHTML = "thankyou " + z + "..";
document.getElementById("case").style.display = 'block';
dis(z);
}
else
document.getElementById("demo").innerHTML = "thankyou";
}
function dis(arg) {
alert("your mark is" + arg);
}
If you want the value to be accessible from independent functions you'll need to store it in a global variable:
<script>
var userName = null;
function display() {
userName = prompt("enter your name...");
if (userName != null) {
document.getElementById("demo").innerHTML="thankyou "+userName +"..";
document.getElementById("case").style.display='block';
} else
document.getElementById("demo").innerHTML="thankyou";
}
function dis() {
var a=document.getElementById("aaa").value;
alert(userName + ", your mark is"+a);
}
</script>
Note that if the functions are completely independent they'll all need to test whether the variable has a value yet. In your case the dis() function is only called from a control that is made visible after a value has been set, but note that the user might click the button again and then cancel - in which case the name will be set back to null but the case element will still be visible.