How to fix Javascript multiplication onchange - javascript

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>

Related

How can I add an value to an input type

How can I add an value to an input type.
I'm currently working on a converter for meter to kilometer, to mile, ...
I've created different input types in my HTML Code and took the value of them in JS, which worked completely fine, and I prevented the page from reloading after I click submit. Now I want to reassign the new, calculated value (kilometer.value = meter / 1000), but this doesn't work.
It works completely fine, when I'm putting an console.log after the variable meter and the first variable kilometer. It logs the correct number - the reassignment just doesn't work.
JavaScript:
const calculateMeter = () => {
let meter = document.getElementById("meter").value;
let kilometer = document.getElementById("kilometer").value;
kilometer.value = meter / 1000;
}
HTML:
<form id="calculator" onsubmit="calculateMeter(); return false">
<label for="kilometer">Kilometer:</label>
<input type="number" id="kilometer"><br>
<label for="meter">Meter:</label>
<input type="number" id="meter"><br>
value of <input> is always a string, but in case of numerical input types, like type="number", or type="range", you can get the number directly using valueAsNumber:
const calculateMeter = () => {
let kilometer = document.getElementById("kilometer").valueAsNumber;
document.getElementById("meter").value = kilometer * 1000;
}
const calculateKilometer = () => {
let meter = document.getElementById("meter").valueAsNumber;
document.getElementById("kilometer").value = meter / 1000;
}
<label for="kilometer">Kilometer:</label>
<input type="number" id="kilometer" oninput="calculateMeter()"><br>
<label for="meter">Meter:</label>
<input type="number" id="meter" oninput="calculateKilometer()"><br>
Did you mean something like, that?
let meterInp = document.getElementById("meter");
let kilometerInp = document.getElementById("kilometer");
meterInp.addEventListener("change", ()=>{
kilometerInp.value = (+meterInp.value)/1000;
});
kilometerInp.addEventListener("change", ()=>{
meterInp.value = (+kilometerInp.value)*1000;
});
<form id="calculator" onsubmit="calculateMeter(); return false">
<label for="kilometer">Kilometer:</label>
<input type="number" id="kilometer" step="0.00001"><br>
<label for="meter">Meter:</label>
<input type="number" step="0.01" id="meter"><br>
</form>
The (+) converts string to number.
for e.g. (+meterInp.value)/1000
You should convert meter to intiger
const calculateMeter = () => {
let meter = document.getElementById("meter").value;
let kilometer = document.getElementById("kilometer").value;
kilometer.value = Number(meter) / 1000;
}

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;
}

JavaScript function for adding up checkboxes from a form

My previous question got closed for a typo, although I'm not sure why as there were more problems in my logic. However, I have edited the loop and I still can not get it working. I need to add up multiple items and enter the answer into the text box, however I cant seem to see a problem.
JavaScript
<script>
"use strict";
const form = document.getElementById('bookingForm');
const total = form.getElementById('total');
const checkboxes = form.querySelectorAll('input[data-price][type=checkbox]');
const cbamount = checkboxes.length;
document.getElementsByName('event[]')[0].onclick = function() {
totalPrice()
};
function totalPrice(){
let totalPrice = 0;
for (let i=0; i< cbamount; i++) {
const box = checkboxes[i];
if (box.checked) {
totalPrice += box.dataset.price;
}//if
}//for
}
document.getElementsByName("txtTotalPrice").value = totalprice;
HTML for the text box
<section id="checkCost">
<h2>Total cost</h2>
Total <input type="text" name="total" size="10" readonly="">
</section>
HTML for the item (there are multiple)
<span class="eventTitle">Winter</span>
<span class="eventStartDate">2020</span>
<span class="eventEndDate">2020</span>
<span class="catDesc">Fam</span>
<span class="venueName">Disc</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="12" data-price="0.00">
there were a number of errors involving case.
you were using form.getElementById instead of document.getElementById
same with form.querySelectorAll instead of document.querySelectorAll
also, you are using getElementsByName which returns an array, so return to only [0].
further: you will likely find an issue with the return being a string, and additional clicks will append to that string rather than adding as numbers.
also: you had document.getElementsByName("txtTotalPrice").value = totalprice;[SIC] outside of the function bracket so it was not being called at the right time.
the example works with minimal fixes though.
const form = document.getElementById('bookingForm');
const total = document.getElementById('total');
const checkboxes = document.querySelectorAll('input[data-price][type=checkbox]');
const cbamount = checkboxes.length;
document.getElementsByName('event[]')[0].onclick = function() {
totalPrice()
};
function totalPrice() {
let totalprice = 0;
for (let i = 0; i < cbamount; i++) {
const box = checkboxes[i];
if (box.checked) {
totalprice += box.dataset.price;
} //if
} //for
document.getElementsByName("txtTotalPrice")[0].value = totalprice;
}
<section id="checkCost">
<h2>Total cost</h2>
Total <input type="text" name="txtTotalPrice" size="10" value="-_-">
</section>
<span class="eventTitle">Winter</span>
<span class="eventStartDate">2020</span>
<span class="eventEndDate">2020</span>
<span class="catDesc">Fam</span>
<span class="venueName">Disc</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="12" data-price="0.00">
.getElementById() only works when called from document, you can't use it from another selection like you had - querySelector / querySelectorAll do work however, so I've used those
document.getElementsByName('event[]')[0] was only selecting the first input, because of [0] - getElementsByName returns a NodeList of elements, which is similar to an Array. I've just used the checkboxes selection you had already defined, as it targeting the same elements
document.getElementsByName("txtTotalPrice").value = totalprice was outside of the function it should have been called in, and so wasn't getting any value passsed to it
Also, it feels redundant that your inputs have a value of 0, but data-price set to your values; is there a reason you can't just use the value attribute here?
I've added a few extra input boxes, and changed the selector for your total input, just to better test this. Feel free to tell me if something isn't right with those
const form = document.getElementById('bookingForm');
const total = document.getElementById('total');
const checkboxes = form.querySelectorAll('input[data-price][type=checkbox]');
checkboxes.forEach((input) => {
input.addEventListener('click', totalPrice);
});
function totalPrice() {
let totalCost = 0;
for (let i = 0; i < checkboxes.length; i++) {
const box = checkboxes[i];
if (box.checked) {
totalCost += parseFloat(box.dataset.price);
}
}
/* Added a cleaner way to find totalCost, if wanted
let totalCost = [...checkboxes].reduce((total, box) => {
return box.checked ? total += parseFloat(box.dataset.price) : total;
}, 0);
*/
total.value = totalCost;
}
<section id="checkCost">
<h2>Total cost</h2>
Total: <input id="total" type="text" name="total" size="10" readonly>
</section>
<form id="bookingForm">
<span class="chosen"><input type="checkbox" name="event[]" value="1.00" data-price="1.00"></span>
<span class="chosen"><input type="checkbox" name="event[]" value="3.50" data-price="3.50"></span>
<span class="chosen"><input type="checkbox" name="event[]" value="5.25" data-price="5.25"></span>
</form>

Issues outputting text via JavaScript

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!

How to handle an input parameter in javascript

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>

Categories