I want to make a webpage that has two text boxes, a Celsius and Fahrenheit box. In between them, there is a convert button which converts Celsius to Fahrenheit and Fahrenheit to Celsius. If there is letters in either box, I want to cancel the converting and an alert pop up saying "Only numbers please!" So far, I haven't figured out how to get the alert and when I type numbers in the Celsius box, it always says the number -18 in the same box. Fahrenheit is fine.
HTML:
<html>
<head>
<title>Temparature Converter</title>
<script type="text/javascript" src="tempconversion.js"></script>
</head>
<body>
Celsius: <input id="c" onkeyup="convert('C')">
<button type="button" id="convert" onclick="convertTemp()">Convert</button>
Fahrenheit: <input id="f" onkeyup="convert('F')">
</body>
</html>
JavaScript:
function convertTemp(degree) {
if (degree == "C") {
F = document.getElementById("c").value * 9 / 5 + 32;
document.getElementById("f").value = Math.round(F);
} else {
C = (document.getElementById("f").value -32) * 5 / 9;
document.getElementById("c").value = Math.round(C);
}
}
Note: I got some code from W3Schools so I think the onkeyup convert is a little funny. If possible, please notify me how it has to change as well as the JavaScript.
There is no need for the onkeyup attributes, since they original code from W3Schools was designed to instantly update values as they were entered.
I did modify the functionality to clear of original value, that way the conversion button can work both ways with a simple code.
Here's a quick JavaScript to do the job:
function convertTemp() {
// Set the initial variables for c (Celsius) and f (Fahrenheit)
var c = document.getElementById('c'), f = document.getElementById('f');
// Test if there is a value for Celsius
if(c.value != '') {
// Set the value for Fahrenheit
f.value = Math.round(c.value * 9 / 5 + 32);
// Clear the value for Celsius
c.value = '';
// If there isn't a value for Celsius
} else {
// Set the value for Celsius
c.value = Math.round((f.value - 32) * 5 / 9);
// Clear the value for Fahrenheit
f.value = '';
}
}
And its accompanying HTML:
Celcius:<input id="c">
Fahrenheit:<input id="f">
<button type="button" id="convert" onclick="convertTemp()">Convert</button>
It can be tested at: http://jsfiddle.net/bhz6uz54/
Something to remember about simple code, like this, there is nothing to verify the supplied values are acceptable. A little regex can act as validation, but how it would be implemented depends on how you want to flag the problem.
I personally hate Do-it Buttons so I'd go with a more dynamic solution:
// Get the Input elements:
var $f = document.getElementById("f");
var $c = document.getElementById("c");
function FC_CF() {
var temp; // Will hold the temperature value
var $targ; // Used to target the element we're not typing into:
if (this.id === "c") { // If we're typing into #c...
$targ = $f; // use #f as target element
temp = (this.value * 9 / 5) + 32; // C2F
} else {
$targ = $c;
temp = (this.value - 32) * 5 / 9; // F2C
}
// Write the result "as we type" in the other ($targ) field:
$targ.value = !isNaN(temp) ? parseFloat(temp.toFixed(1)) : "Err";
// (Above:) temp is a num ? return floated number, else: "Show some error"
}
// Assign input listeners to trigger the above function:
$f.oninput = FC_CF;
$c.oninput = FC_CF;
Celcius: <input id="c">
Fahrenheit: <input id="f">
You can separate the functions which do the temperature conversion as follows i did somw changes in the code.
<p>
<label>Fahrenheit</label>
<input id="outputFahrenheit" type="number" placeholder="Fahrenheit"
oninput="temperatureConverterCelsius(this.value)"
onchange="temperatureConverterCelsius(this.value)" value="">
</p>
<p>Celsius: </p>
<input id="outputCelsius" type="number" placeholder="Celsius"
oninput="temperatureConverterFahrenheit(this.value)"
onchange="temperatureConverterFahrenheit(this.value)" value="">
</p>
<script type=""text/javascript>
function temperatureConverterCelsius(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelsius").value = (valNum-32) / 1.8;
//document.getElementById("outputFahrenheit").value = (valNum*1.8)+32;
}
</script>
</body>
</html>
class Temperature_conversation {
constructor(celsius) {
this.celsius= celsius;
this.fahrenheit= 0;
this.table_begin= -50.0;
this.table_end= 50.0;
this.table_step= 10.0;
console.log('---------------------Conversion--------------------------');
console.log('Celsius fahrenheit');
for(this.celsius = this.table_begin; this.celsius <= this.table_end; this.celsius += this.table_step){
this.fahrenheit = this.celsiusToFahrenhit(celsius);
}
}
celsiusToFahrenhit(c){
const minimun_celsius = -273.15;
if (c < minimun_celsius) {
throw 'O argumento es pequeno';
}
this.celsius = (9.0 / 5.0) * c+ 32;
var res = [this.celsius, this.fahrenheit]
console.table(res);
}
}
Related
I am new to learning these languages, and everything looks syntactically correct. The issue I'm having is that the correct button will just keep click as correct rather or not the answer is correct or not. The tables are updating, but I'm not sure where the issue is. The if-else statement looks to be okay (I know I don't need the else if in there). If anyone could help me figure out what is wrong I would appreciate it.
window.onload = function() {
equations();
};
window.onload = equations;
var sum;
var correct = 0,
incorrect = 0;
function equations() {
var a, b, sum;
//assign random values to a,b
a = Math.floor(Math.random() * 10) + 1;
b = Math.floor(Math.random() * 10) + 1;
//array that holds values, MUST BE MUTUABLE
solve = [a + b, a - b, a / b, a * b];
signs = ['+', '-', '÷', 'x'];
//assign random opperation
let randoArr = Math.floor(Math.random() * solve.length)
sum = solve[randoArr];
showSign = signs[randoArr];
//show in html
document.getElementById('showMath').innerHTML = a + showSign + b;
//This will be used to reassign the value to global variable
window.sum = sum;
console.log(sum);
return (sum)
};
// Function checks if user Input is correct and then adds tallies to the table.
// The tables values are held in correct and incorrect and incremented based on the conditional statement.
function confirmIfRight() {
var userInput = document.getElementById('userInput').value;
const correctEl = document.getElementById('correctCount');
const incorrectEl = document.getElementById('incorrectCount');
sum = equations();
if (userInput = sum) {
correct++;
correctEl.textContent = correct;
equations();
} else if (userInput = '') {
incorrect++;
incorrect.textContent = incorrect;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
clearTextBox();
}
//This function is used to clear the textbox
function clearTextBox() {
document.getElementById('userInput').value = "";
}
<body>
<!--Equations load when web page is loaded up. -->
<script>
window.onload = function() {
equations();
};
</script>
<h1> Welcome to Fast Math! </h1>
<p> A website for solving simple math problems. </p>
<!-- Math Stuff-->
<div id="showMath">
</div>
<!-- ANSWERS GO HERE -->
<form>
<input type="input" id="userInput" />
<input type="button" id="submit" value="Enter" onclick="confirmIfRight()" onclick="document.getElementById('userInput').value = '' " />
</form>
<!-- Score tally-->
<table>
<tr>
<td><b>Correct</b></td>
<td><b>Incorrect</b></td>
</tr>
<tr>
<td id="correctCount"> 0 </td>
<td id="incorrectCount"> 0 </td>
</tr>
</table>
</body>
The main reason your code wasn't working is because you aren't using the equality operator (==), you are using the assignment operator (=) in your if..else statements. Fixing that alone should resolve the main problem in your question.
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else if (userInput == '') {
incorrect++;
incorrect.textContent = incorrect;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
However, this presents another problem in your code immediately: you're comparing sum immediately after reassigning it in confirmIfRight(). A new equation will have been generated prior to the comparison. This means the value in sum will most likely not be correct considering the original equation presented and the answer given.
To resolve this, remove the sum = equations(); line just before the if..else statements:
//sum = equations();
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else if (userInput == '') {
incorrect++;
incorrect.textContent = incorrect;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
Additionally, I do agree that you can remove the else if section and this should capture all cases where the answer does not equal the expected result.
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
Testing a few times showed that this is all you need to have your code working. Run the code snippet below as an example:
window.onload = equations;
var sum;
var correct=0, incorrect=0;
function equations(){
var a,b,sum;
//assign random values to a,b
a = Math.floor(Math.random() * 10) + 1;
b = Math.floor(Math.random() * 10) + 1;
//array that holds values, MUST BE MUTUABLE
solve = [a+b , a-b ,a /b ,a *b ];
signs = ['+', '-','÷','x'];
//assign random opperation
let randoArr = Math.floor(Math.random()*solve.length)
sum=solve[randoArr];
showSign=signs[randoArr];
//show in html
document.getElementById('showMath').innerHTML = a + showSign + b;
//This will be used to reassign the value to global variable
window.sum = sum;
console.log(sum);
return(sum)
};
// Function checks if user Input is correct and then adds tallies to the table.
// The tables values are held in correct and incorrect and incremented based on the conditional statement.
function confirmIfRight(){
var userInput = document.getElementById('userInput').value;
const correctEl = document.getElementById('correctCount');
const incorrectEl= document.getElementById('incorrectCount');
//sum = equations();
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
clearTextBox();
}
//This function is used to clear the textbox
function clearTextBox() {
document.getElementById('userInput').value = "";
}
<!--Equations load when web page is loaded up. -->
<script>
window.onload = function(){
equations();
};
</script>
<h1> Welcome to Fast Math! </h1>
<p> A website for solving simple math problems. </p>
<!-- Math Stuff-->
<div id="showMath">
</div>
<!-- ANSWERS GO HERE -->
<form>
<input type="input" id="userInput"/>
<input type="button" id ="submit" value="Enter"onclick="confirmIfRight()" onclick=
"document.getElementById('userInput').value = '' "/>
</form>
<!-- Score tally-->
<table>
<tr>
<td><b>Correct</b></td>
<td><b>Incorrect</b></td>
</tr>
<tr>
<td id="correctCount"> 0 </td>
<td id="incorrectCount"> 0 </td>
</tr>
</table>
There were a few mistakes that you did. The main issue was that you were generating a new equation and sum value every time you call equations function.
So I've saved the value in a new hidden input that is visually hidden from the user. And then compare it to the user input value. There is a plus sign in front of some methods and it is to convert the value to a number. Also, I allowed myself to make a few code naming changes so the code can feel better. Also, you can remove the return statement in the equation method since it has no reason to be there anymore.
let correct = 0,
incorrect = 0;
function generateEquation() {
var a, b, sum;
//assign random values to a,b
a = Math.floor(Math.random() * 10) + 1;
b = Math.floor(Math.random() * 10) + 1;
//array that holds values, MUST BE MUTUABLE
solve = [a + b, a - b, a / b, a * b];
signs = ["+", "-", "÷", "x"];
//assign random opperation
let randoArr = Math.floor(Math.random() * solve.length);
sum = solve[randoArr];
showSign = signs[randoArr];
//show in html
document.getElementById("showMath").innerHTML = a + showSign + b;
//This will be used to reassign the value to global variable
window.sum = sum;
document.getElementById("hiddenInput").value = sum;
return sum;
}
// The tables values are held in correct and incorrect and incremented based on the conditional statement.
function isCorrect() {
let userInput = +document.getElementById("userInput").value;
const correctEl = document.getElementById("correctCount");
const incorrectEl = document.getElementById("incorrectCount");
if (userInput === +document.getElementById("hiddenInput").value) {
correct++;
correctEl.textContent = correct;
generateEquation();
} else if (userInput == "") {
incorrect++;
incorrect.textContent = incorrect;
generateEquation();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
generateEquation();
}
clearTextBox();
}
//This function is used to clear the textbox
function clearTextBox() {
document.getElementById("userInput").value = "";
}
generateEquation();
<!DOCTYPE html>
<html lang="eng">
<head>
<link rel="stylesheet" href="fastmath_style.css" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial scale = 1" ; />
<title>Fast Math</title>
</head>
<body>
<h1>Welcome to Fast Math!</h1>
<p>A website for solving simple math problems.</p>
<!-- Math Stuff-->
<div id="showMath"></div>
<!-- ANSWERS GO HERE -->
<form>
<input type="input" id="userInput" />
<input type="hidden" id="hiddenInput" />
<input
type="button"
id="submit"
value="Enter"
onclick="isCorrect()"
onclick="document.getElementById('userInput').value = '' "
/>
</form>
<!-- Score tally-->
<table>
<tr>
<td><b>Correct</b></td>
<td><b>Incorrect</b></td>
</tr>
<tr>
<td id="correctCount">0</td>
<td id="incorrectCount">0</td>
</tr>
</table>
<script src="./app.js"></script>
</body>
</html>
I have an input element whose value is a number between 0 and 100. I am attempting to style the element via a two-color scale, taking its value as the input.
I am planning on making a simple gradient:
When the number is 100, the element's background color is green #00ff00
When the number is 0, it is red #ff0000
When the number is 50, it displays a yellow color #ffff00
The in-between values should be colored according to the scale.
I have tried using an if statement in JavaScript, but that fails to create a gradient, as there is a hard border between red, yellow, and green (sans gradient). See the code below:
var x = 0;
function color() {
x = document.getElementById("color").value;
console.log(x);
if (x > 50) {
document.getElementById('color').style.backgroundColor = "#00ff00";
}
else if (x == 50) {
document.getElementById('color').style.backgroundColor = "#ffff00";
}
else {
document.getElementById('color').style.backgroundColor = "#ff0000";
}
}
<button onclick="color();">Run</button>
<input type="number" id='color' value=50></input>
<!-- The input is not disabled for value debugging. -->
Is there concise way to perform this task?
const updateColor = (target) => {
const value = target.value;
//#00ff00 100
//#ffff00 50
//#ff0000 0
const R = Math.round((255 / 50) * (value < 50 ? 50 : 100 - value)).toString(16)
const G = Math.round((255 / 50) * (value > 50 ? 50 : value)).toString(16)
const twoDigit = (d) => ("0" + d).slice(-2);
const nextColor = '#' + twoDigit(R) + twoDigit(G) + '00';
target.style.background = nextColor
}
document.getElementById('color').addEventListener('change', (e) => updateColor(e.target));
document.addEventListener("DOMContentLoaded", function (event) {
updateColor(document.getElementById('color'))
});
<html>
<body>
<input type="number" id="color" min="0" max="100" value="0">
</body>
</html>
You can use Html Range input for this purpose and Use javascript for getting its value. Like:
<input id="myId" type="range" min="0" max="100">
Use Javascript to get its value by using its ID. Use a Javascript function. Either call it using a button or add onchange event.
You are just missing a style property...
just do this
document.getElementById("color").style.background = "Any Color";
or if you want to change text color then
document.getElementById("color").style.color = "Any Color";
Here I wrote full code for your problem:-
<input type="number" id="color" min="0" max="100" onkeyup="check()">
<script>
function check(){
c = document.getElementById("color");
x = c.value;
if(x==0)
c.style.background="Red";
else if(x==50)
c.style.background = "Yellow";
else
c.style.background = "Green";
}
</script>
I have found the optimal way to create a 2 color scale that uses vibrant, hexadecimal colors:
var colval = 0;
var R = 0;
var G = 0;
var B = 0;
function check() {
c = document.getElementById("color");
x = c.value;
if (x > 50) {
R = Math.round(-0.051 * x ** 2 + 2.55 * x + 255);
G = 255;
} else if (x < 50) {
R = 255;
G = Math.round(-0.051 * x ** 2 + 7.65 * x + 0);
} else {
R = 255;
G = 255;
}
B = 0;
colval = "#" + R.toString(16) + G.toString(16) + "00";
c.style.background = colval;
}
<html>
<body>
<input type="number" id="color" min="0" max="100" value="0" onkeyup="check()">
</body>
</html>
Why is this not working. There are no errors in console and compiler does not show anything specific. Probably something wrong with the variable check?
document.getElementById("checknumber").onclick = function() {
var numberSelected = document.getElementById("input").value;
//alert(numberSelected)
var number = Math.floor((Math.random() * 6) + 1);
//alert(number)
if (input == number) {
alert("got it");
} else("noup not now");
}
<p>Guess the number: </p>
<p><input id="input"> </p>
<p><button id="checknumber">Check !</button></p>
The input variable is not defined anywhere, and I think you missed an alert in the else("noup not now") statement.
Side note: you are confronting a String with a Number, in this case it behave as expected because of Js Coercion and the equality operator.
document.getElementById("checknumber").onclick = function() {
var numberSelected = document.getElementById("input").value;
//alert(numberSelected)
var number = Math.floor((Math.random() * 6) + 1);
//alert(number)
if (numberSelected == number) {
alert("got it");
} else {
alert("noup not now");
}
}
<p>Guess the number: </p>
<p><input id="input"> </p>
<p><button id="checknumber">Check !</button></p>
I want to get input from user, multiply it by 1.3 for example and output to window instantly, like as user types function is executing and displaying in it in HTML instantly. How do it do it?
Here my code
function calc() {
amount = document.getElementById("amount").value;
num2 = 1.3;
document.getElementById("result").innerHTML = amount * num2;
return result;
}
<input id='amount', type="text" >
<button onclick="calc()"> Buy Now! </button>
<p> Result is: <br>
<span id = "result"> </span>
<input type="text"onkeyup="calc()">
First off, you got some invalid HTML:
What's that comma?
<input id='amount', type="text" >
Attributes don't need any separator — just put a space:
<input id='amount' type="text" >
Getting rid of pointless spaces, a cleaner HTML fragment follows:
<input id='amount' type="text">
<button onclick="calc()">Buy Now!</button>
<p>Result is:<br>
<span id="result"></span>
Now, let's try to list some options:
The keydown and keypress events won't work because they're fired before value changes.
The keyup event, as suggested #Dmitri Usanov, will work only partially: it is called when the key releases (not as soon as the text is updated) and if you e.g. paste by right-clicking then it won't fire.
The input is the solution. Note that it requires HTML5.
Working demo:
function calc() {
// Let's convert the input text to a number.
const amount = +document.getElementById("amount").value;
// The number to multiply by.
const num2 = 1.3;
// The number of decimal places we wish to truncate at.
const precision = 2;
const scale = 10 ** precision;
return Math.round(amount * num2 * scale) / scale;
}
window.addEventListener("load", () => {
const outputSpan = document.getElementById("result");
document.getElementById("amount").addEventListener("input", () => {
outputSpan.innerHTML = calc(this.value);
});
});
<input id='amount' type="text">
<button onclick="calc()">Buy Now!</button>
<p>Result is:<br>
<span id="result"></span>
Try this
function calc(isEsc) {
const num2 = 1.3;
let result = document.getElementById("result"),
amount = document.getElementById("amount");
if (isEsc) {
result.innerHTML = 0;
amount.value = '';
} else {
result.innerHTML = amount.value * num2;
}
}
document.onkeyup = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key == "Escape" || evt.key == "Esc");
} else {
isEscape = (evt.keyCode == 27);
}
calc(isEscape);
};
<input type="text" id="amount" />
<span id="result">0</span>
I'm new here, and very new to Javascript and programming concepts in general. Part of the form I'm working on simlpy needs to calculate the difference between two prices. I do know float numbers are screwy, so I have that part figured out. And it calculates, and inputs it into field 3. The only thing I can't seem to figure out is making it so that if either field 1 or 2 is empty, the function doesn't run. It should only run when both fields are filled. Here's my example code:
<input type="text" id="1"> </input><br/>
<input type="text" id="2"> </input><br/>
<input type="text" id="3"> </input><br/>
<br/><br/><br/>
<p id="test"></p>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
function emptyCheck(){
if ($("#1") = ""){
$("#3").val("");
}
else if ($("#2") = ""){
$("#3").val("");
}
else{
rateDiff();
}
}
function rateDiff(){
var clientRate = $("#1").val() * 100;
var agentRate = $("#2").val() * 100;
var fareDiff = clientRate - agentRate;
var fareDiffDec = fareDiff / 100;
$("#3").val(fareDiffDec.toFixed(2));
}
$("#1").keyup(emptyCheck);
$("#2").keyup(emptyCheck);
</script>
I don't get what I'm doing wrong here. Can anyone point me in the right direction?
if ($("#1") = ""){
should be
if ($("#1").val() == ""){
same for $("#2") = ""
$("#1") is a jquery element, not the value.
Also you put = instead of ==
$("#1") = "")
Should be
$("#1").val() == "")
One = is used to assign a value, while two == is to do a comparison.
Just use the "falsey" of JavaScript and the values:
function emptyCheck(){
if (!$("#1").val() || !$("#2").val()){
$("#3").val("");
}
else{
rateDiff();
}
}
NOTE: you would be better parsing the numbers to handle alpha entry:
function emptyCheck() {
if (!parseFloat($("#1").val()) || !parseFloat($("#2").val())) {
$("#3").val("");
} else {
rateDiff();
}
}
function rateDiff() {
var clientRate = parseFloat($("#1").val()) * 100;
var agentRate = parseFloat($("#2").val()) * 100;
var fareDiff = clientRate - agentRate;
var fareDiffDec = fareDiff / 100;
$("#3").val(fareDiffDec.toFixed(2));
}
$("#1").keyup(emptyCheck);
$("#2").keyup(emptyCheck);