I wrote a code to change values in Fahrenheit to Celsius using Javascript.
<p id = "result"> </p> // The result will appear here
<script>
function toCelsius(f) {
return (f-32) * 5/9;
}
document.getElementById("result").innerHTML = toCelsius(77);
</script>
I checked this code, and it works on my Eclipse.
However, instead of putting the value directly, I want to input a number in Fahrenheit and change that into Celsius.
I added the following.
<form id="frm1">
Enter a number : <input type="text" name=fahrenheit> <br>
<input type=button" onclick="toCelsius(frm1)" value="change"> // I need some help for handling parameter here
</form>
I want to make it as simple as possible like below.
Could anyone give me some tips on how to handle an input parameter?
I spotted a few problems.
There were some syntax issues in writing HTML attributes
The code that changes innerHTML of result won't get invoked when the button is clicked. Rather, it'll get invoked only once, the first time the script is run. To fix this, I placed that line in a function which would be called when the button is clicked. Please look at the change button action.
<p id="result"></p>
<script>
function toCelsius(f) {
return (f - 32) * 5 / 9;
}
function changeClicked() {
var input = document.getElementById("fahrenheit").value;
if (parseInt(input) === null) return;
document.getElementById("result").innerHTML = toCelsius(input);
}
</script>
<form id="frm1">
Enter a number : <input type="text" id="fahrenheit" name="fahrenheit"> <br>
<input type="button" onclick="changeClicked()" value="change">
</form>
Add an event listener for the button then call your toCelsius() function with passing the input value to it.
function toCelsius(f) {
return (f - 32) * 5 / 9;
}
document.getElementById('btn_change').addEventListener('click', function() {
var fahrenheit = document.getElementsByName('fahrenheit')[0].value;
document.getElementById('result').innerHTML = toCelsius(fahrenheit);
});
<form id="frm1">
Enter a number : <input type="text" name=fahrenheit> <br>
<input type="button" id="btn_change" onclick="toCelsius(frm1)" value="change">
</form>
<p id="result"> </p>
// Give input tag an id of "number"
Enter a number : <input type="text" name=fahrenheit id ="number"> <br>
// Then,
<script>
let number = document.getElementById("number").value;
function toCelsius(f) {
return (f-32) * 5/9;
}
document.getElementById("result").innerHTML = toCelsius(number);
</script>
<!-- The result will be displayed here -->
<p id="result" style="min-height: 20px"></p>
<input type="number" name="fahrenheit">
<input type="button" class="convert-to-celsius-btn" value="Convert to C">
<script>
var convertBtn = document.querySelector(".convert-to-celsius-btn");
var fahrenheitInput = document.querySelector("input[name=fahrenheit]");
var resultEl = document.querySelector("#result")
function toCelsius(f) {
return (f-32) * 5/9;
}
function convertToCelsius() {
var fahrenheit = fahrenheitInput.value;
// input validatation code goes here ...
// next convert to celsius
var celsius = toCelsius(fahrenheit)
// now show the value in the DOM
celsius = celsius.toFixed(2);
resultEl.textContent = celsius + " C"
}
convertBtn.addEventListener("click", convertToCelsius);
</script>
Related
I'm still learning and am trying to simply take a number from an input, add 7 to it, and then display it on the webpage. It all works fine, but what I don't like is if you hit "submit" without entering a number, the HTML field shows "NaN" vs. a custom message, which is what I'd like to do.
Here's the code I have so far. What am I missing to capture that nothing was entered and return a different message?
function add7() {
let number = document.getElementById('num').value;
let addition = 7;
if (isNaN(number)){
document.getElementById("add").innerHTML ="Please enter a value";
}
else {
let original = parseInt(number,10);
num = addition + original;
document.getElementById("add").innerHTML = num;
}
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add"></p>
</div>
That is because an empty string actually returns true when passed to isNaN(), i.e. isNaN('') returns true.
To do that, you can simply move the check to the final step, a.k.a. evaluate the num variable instead:
function add7() {
let number = document.getElementById('num').value;
let addition = 7;
let original = parseInt(number, 10);
let num = addition + original;
if (isNaN(num)) {
document.getElementById("add").innerHTML = "Please enter a value";
return;
}
document.getElementById("add").innerHTML = num;
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add">
</p>
</div>
Alternatively, you can also simply parse the input element's value directly: it will inform you if it is not a number right away:
function add7() {
let number = parseInt(document.getElementById('num').value, 10);
if (isNaN(number)) {
document.getElementById("add").innerHTML = "Please enter a value";
return;
}
let addition = 7;
let num = addition + number;
document.getElementById("add").innerHTML = num;
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add">
</p>
</div>
https://codepen.io/kev_daddy/pen/MMWEMG
I am building a form that is meant to update the difference between two values in real time (ie without refreshing the page). It is comprised of multiple fields, but ultimately I'll be getting the sum of two values, and displaying this using HTML.
The entire thing appears to work as intended until I get to the function that is meant to display the sum in html.
The intention is that the result (a hidden field) is shown as plain text in output. It doesn't trigger on the onset, however if i punch in an extra character using my keyboard, the event is finally heard and the text shows. up.
I am sure that I am missing something, but how do I ensure that the sum is outputted?
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0;
var y = document.getElementById('content').value || 0;
var result = document.getElementById('result');
var myResult = parseInt(x) + parseInt(y);
result.value = myResult; }
var input = document.getElementById("result");
var output = document.getElementById("output"); input.addEventListener("input", function() {
output.innerText = this.value;
});
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
<hr>
<p>You can earn <span id="output"></span> more!
There is no input event on span. You can create a separate function and pass the value of the calculation to this function whose responsibility will be to update the span text content
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0;
var y = document.getElementById('content').value || 0;
var result = document.getElementById('result');
var myResult = parseInt(x) + parseInt(y);
result.value = myResult;
updateText(myResult)
}
function updateText(val) {
document.getElementById("output").innerText = val;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
<hr>
<p>You can earn <span id="output"></span> more!
I'm not sure why my code isn't multiplying the two numbers when I change them. Once I enter a number in the Multiplier field, the onchange function continues adding values and if its a null value, it enters "NaN"
<body>
<h1>Mutiply</h1>
<p>Multiplicand: <input type="text" id="multiplicand" value="0" onchange="multiply()"></p>
<p>Multiplier: <input type="text"/ id="multiplier" value="0" onchange="multiply()"></p> <br>
<div>
<p><span id="showMulipicand">0</span>
×
<span id="showMultiplier">0</span> = <span id="showProduct">0</span></p>
</div>
<script src="multiply.js"></script>
multiply() {
var multiplicand = document.getElementById('multiplicand').value;
var multiplier = document.getElementById('multiplier').value;
var showProduct = parseInt(multiplicand) * parseInt(multiplier);
var p = document.getElementById('showProduct');
p.innerHTML += showProduct;
}
You are appending the result to the content of your p tag.
If you just want to show the result, you have to override the innerHTML instead of appending to it.
p.innerHTML = showProduct;
Also, if you want to update the result as you type, use the oninput event instead of onchange which will only trigger when you leave the <input> field.
If you also want to update the multiplier and multiplicand fields, just do the same as for the product:
document.getElementById('showMulipicand').innerHTML = multiplicand;
To avoid NaN problems, when you read the multiplier/multiplicand from the <input>, do a logical or with 0, this way, if the field is blank, its value will be 0.
You should also change the <input> type from text to number.
Here is the code for showing the multiplication result:
function multiply() {
const multiplicand = document.getElementById('multiplicand').value || 0;
const multiplier = document.getElementById('multiplier').value || 0;
const product = parseInt(multiplicand) * parseInt(multiplier);
document.getElementById('showMulipicand').innerHTML = multiplicand;
document.getElementById('showMultiplier').innerHTML = multiplier;
document.getElementById('showProduct').innerHTML = product;
}
<h1>Mutiply</h1>
<p>Multiplicand: <input type="number" id="multiplicand" value="0" oninput="multiply()"></p>
<p>Multiplier: <input type="number" id="multiplier" value="0" oninput="multiply()"></p>
<p>
<span id="showMulipicand">0</span> ×
<span id="showMultiplier">0</span> = <span id="showProduct">0</span>
</p>
I want to create a randomly generated number, ask the user to enter a number, then compare the two and then show a popup telling whether or not they match. This is my code
function myFunction() {
var num=document.getElementById("demo").innerHTML = Math.floor(1000 + Math.random() * 9000);
}
function myFunction1() {
var secondInput = document.getElementById("demo1").value;
if( num === secondInput)
{
window.alert("Same");
}
else
{
window.alert("Don't do that again cvv");
}
<button onclick="myFunction()">press the button to see the code</button>
<p id="demo"></p>
code: <input type="text" name="code" required/><br/><br/>
<button onclick="myFunction1()">Compare</button>
<p id="demo1"></p>
This code works. Please know that there were a couple of improvements:
You referenced to myFunction() before the javascript is loaded.
You need to keep the var num in global scope if you want to reference it in other places, without passing them as an argument.
When comparing values, make sure to select the right input field and to convert the value string to a Number.
var num;
function myFunction() {
num=document.getElementById("demo").innerHTML = Math.floor(1000 + Math.random() * 9000);
}
document.getElementById("button1").addEventListener('click', myFunction)
document.getElementById("button2").addEventListener('click', myFunction1)
function myFunction1() {
var secondInput = document.getElementById("demo1").value;
if( num === +secondInput) {
window.alert("Same");
}
else {
window.alert("Don't do that again cvv");
}
}
<button id="button1" >press the button to see the code</button>
<p id="demo"></p>
code: <input id="demo1" type="text" name="code" required/><br/><br/>
<button id="button2">Compare</button>
<p></p>
First you have to define num in the global scope to be accessable by the two functions and you have to make the first function just show the number without generating a new number every time.
var num;
function show() {
document.getElementById("demo").innerHTML = num;
}
function randomizeAndCompare() {
num = Math.floor(1000 + Math.random() * 9000);
var secondInput = document.getElementById("demo1").value;
if( num === secondInput){
window.alert("Same");
}
else{
window.alert("Don't do that again cvv");
}
}
<button onclick="show()">press the button to see the code</button>
<p id="demo"></p>
code: <input type="text" name="code" required/><br/><br/>
<button onclick="randomizeAndCompare()">Compare</button>
<p id="demo1"></p>
There are a couple of tings here.
First, myFunction1() isn't closed. You should also rename it to something more meaningful, like "compareValue()". That way it is easier to read the code.
You also aren't making a comparison of the two numbers in your compareValue()-function. Your 'num' variable isn't defined. You are also trying to extract the user input value from the button.
See my suggestion for changes:
function generateRandom() {
document.getElementById("demo").innerHTML = Math.floor(1000 +
Math.random() * 9000);
}
function compareValues() {
var num = document.getElementById("demo").innerHTML;
var input = document.getElementById("number").value;
if( num === input)
{
window.alert("Same");
}
else
{
window.alert("Don't do that again cvv");
}
}
HTML:
<button onclick="generateRandom()">press the button to see the code</button>
<p id="demo"></p>
code: <input id="number" type="text" name="code" required/><br/><br/>
<button onclick="compareValues()">Compare</button>
<p id="demo1"></p>
My full code can be found here: http://pastebin.com/t3JCBRrX
I made an easy calculation script for my website. I'd like two modifications but I can't seem to do it.
This is what I have now:
The function:
var ap,result;
function setValue() {
ap = Number(document.getElementById('ap').value);
}
function bereken(){
setValue();
result = (((ap*275)/(ap*275))*1200+(ap*275) || 0).toFixed(e);
document.getElementById('e').value = result;
}
The form:
<label for="e" id="answer">Kosten: </label>
<input type="field" name="Antwoord" id="e" disabled><br>
<input type="button" onclick="bereken()" value="Bereken">
I'd like to prefix the result with a euro sign (result is '€123' instead of '123').
I would also like the result to be just plain text, instead of a disabled input field.
Any help would be greatly appreciated, as I'm just a beginner. Thanks!
edit: the calculation is that complicated because I don't want the answer to be '1200' when '0' has been entered
See this FIDDLE
Just insert the value with '€' appended
document.getElementById('e').innerHTML = '€'+result;
Also you can change the disabled input to label if you want it to be plain text
var ap, result;
function setValue() {
ap = Number(document.getElementById('ap').value);
}
function bereken() {
setValue();
result = (((ap * 275) / (ap * 275)) * 1200 + (ap * 275) || 0).toFixed(e);
document.getElementById('e').innerHTML = '€' + result;
}
<input type='text' id='ap' placeholder='enter value' />
<label for="e" id="answer">Kosten:</label>
<label type="field" name="Antwoord" id="e" disabled></label> <br>
<input type="button" onclick="bereken()" value="Bereken">
change document.getElementById('e').value = result; to document.getElementById('e').value = "€"+result;.
change disabled to readonly.
Try this:
JS Code:
var ap,result;
function setValue() {
ap = Number(document.getElementById('ap').value);
}
function bereken(){
setValue();
result = (((ap*275)/(ap*275))*1200+(ap*275) || 0).toFixed(e);
document.getElementById('e').innerHTML = result;
}
HTML Code:
<input type="text" id="ap"/>
<label for="e" id="answer">Kosten: </label>
<span>€</span><span id="e"> </span><br>
<input type="button" onclick="bereken()" value="Bereken"/>