Bootstrap form outputting wrong results - javascript

Despite not being linked (to my knowledge), when inputting the Celsius number, the Fahrenheit formula will run and be implemented to the Celsius output, with the correct formula being outputted on the Fahrenheit output, and vice versa when inputting a Fahrenheit number.
Image
I have tried several if statements but they only seem to work for one of the outputs with the other having no value result at all.
**HTML//Bootstrap**
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">C°</span>
<input type="number" class="form-control" id="cAmount" placeholder="Celsius">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">F°</span>
<input type="number" class="form-control" id="fAmount" placeholder="Fahrenheit">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Celsius Temperature</span>
<input type="number" class="form-control" id="celsius-result" disabled>
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Fahrenheit Temperature</span>
<input type="number" class="form-control" id="f-res" disabled>
</div>
</div>
**Javascript**
let formSubmit = document.querySelector('#tempCalculator')
formSubmit.addEventListener('submit', runEvent);
function runEvent(e) {
let celInput = document.querySelector('#cAmount');
let fahInput = document.querySelector('#fAmount');
let celResult = document.querySelector('#celsius-result')
let fahResult = document.querySelector('#f-res');
//input
let fahVal = parseFloat((celInput.value * 9/5) + 32);
let celVal = parseFloat((fahInput.value - 32) * 5/9);
//output
celResult.value = celVal.toFixed(2);
fahResult.value = fahVal.toFixed(2);
//stop form refreshing
e.preventDefault();
}
Expected would be just to have one correct value appear in the corresponding output, this does happen, but an incorrect value appears in the unexpected output.
Here's a Codepen link for the full application: https://codepen.io/str-99/pen/NmwXJz

If I'm understanding you correctly this is one way to accomplish what you're trying:
let formSubmit = document.getElementById('tempCalculator');
formSubmit.addEventListener('submit', runEvent);
function runEvent(e) {
let celInput = document.querySelector('#cAmount');
let fahInput = document.querySelector('#fAmount');
let celResult = document.querySelector('#celsius-result')
let fahResult = document.querySelector('#f-res');
//input
let fahVal = parseFloat((celInput.value * 9/5) + 32);
let celVal = parseFloat((fahInput.value - 32) * 5/9);
//output
celResult.value = Number(fahInput.value) > 0 ? celVal.toFixed(2) : '';
fahResult.value = Number(celInput.value) > 0 ? fahVal.toFixed(2) : '';
//reset input boxes
document.getElementById('cAmount').value = '';
document.getElementById('fAmount').value = '';
e.preventDefault();
}
The ternary operator works great for instances like this. We can simply change the value to an empty string when it's not the right/desired input. And for added measure clearing out the input boxes to 'reset' after each calculation.

Related

How to subtract X hours to a time field

I would like to output in a div the result of a math calculation (subtract). In the specific I have a form with a <input type="time" id="time" name="time"> that let user pick up a time. I would like to display in another div the result of the chosen time - 3 Hours.
So if time chosen is 13:00 I would like to output in the div with class result-1 10:00.
How can I achieve this in JS?
<form action="/action_page.php">
<label>Time:</label>
<input type="time" id="time" name="time">
</form>
<div>
<h1>Dispaly the result of Time - 3 Hours</h1>
<div class="result-1">Result</div>
</div>
What I tried is to replicate what explained here but without result?
When you read data from the <input> element, the math library cannot be used directly because it reads data of type String. So I developed two different solutions that exhibit two different behaviours.
Behaviour-1
The following solution extracts the selected time value based on a time stored in the secondTime array.
const time1 = document.getElementById('time1');
let result = document.getElementById('result');
// If you want to calculate the difference to the fixed time point,
// change the contents of the secondTime array.
let firstTime = []; secondTime = ["03", "00"]
// Function that prints the time difference to the DOM
function calculate() {
if(firstTime.length != 0) {
var hours = firstTime[0] - secondTime[0];
var minutes = firstTime[1] - secondTime[1];
result.innerHTML = "";
result.insertAdjacentHTML("beforeend", `${hours}:${minutes}`);
}
}
// Event fired when <input> element changes
time1.onchange = function() {
firstTime = this.value.split(":");
calculate();
}
#result {
color: red;
}
<form action="/action_page.php">
<label>First Time:</label>
<input type="time" id="time1" name="time">
</form>
<div>
<h1>Dispaly the result of Time - 3 Hours</h1>
<div class="result-1">Result: <span id="result"></span></div>
</div>
Behaviour-2
In the solution below, the value in the <input> element is parsed using the String.prototype.split() method and the time difference is calculated using the calculate() method. Edit the calculate() method for more accurate calculation.
const time1 = document.getElementById('time1');
const time2 = document.getElementById('time2');
let result = document.getElementById('result');
let firstTime = [], secondTime = [];
function calculate() {
if(firstTime.length != 0 && secondTime.length != 0) {
var hours = secondTime[0] - firstTime[0];
result.innerHTML = "";
result.insertAdjacentHTML("beforeend", `${hours} Hours`);
}
}
time1.onchange = function() {
firstTime = this.value.split(":");
calculate();
}
time2.onchange = function() {
secondTime = this.value.split(":");
calculate();
}
#result {
color: red;
}
<form action="/action_page.php">
<label>First Time:</label>
<input type="time" id="time1" name="time">
<label>Second Time:</label>
<input type="time" id="time2" name="time">
</form>
<div>
<h1>Dispaly the result of Time - 3 Hours</h1>
<div class="result-1">Result: <span id="result"></span></div>
</div>
First you should convert string time to integers then you can subtract.
<html>
<script>
function subTime(t,x) {
var t1 = t.split(':');
var x1 = x.split(':');
var tx0 =parseInt(t1[0])- parseInt(x[0]);
var tx1 =parseInt(t1[1])- parseInt(x[1]);
if(tx1<0){tx1+=60;tx0--;}
if(tx0<0){tx0+=12}
if(tx0<10){tx0="0"+tx0}
if(tx1<10){tx1="0"+tx1}
return tx0+":"+tx1;
}
function showTime(e){
var x = "3"+"00";
document.getElementById('res').innerText = subTime(e.target.value, x)
}
</script>
<body>
<input type="time" id="time" onChange='showTime(event);'/>
<div id='res'></div>
</body>
</html>

Calculate price based on markup and markup based on price using the same input fields

I have created 3 input fields Trade, Markup and Price. I would like for the user to enter a trade and then manipulate the price either by markup or by entering the price and the markup showing a reflection of that price.
I would like the calculation to be live and to not have to submit a button everytime to view changes.
I did split the code up into 2 separate scripts but that did not make a difference and I have also changed the addEventListeners to "change" but that still did not work. I have a felling I will need to add a IF statement between the 2 results somehow.
document.getElementById("trade").addEventListener("change", calculation);
document.getElementById("price").addEventListener("change", calculation);
document.getElementById("markup").addEventListener("change", calculation);
function calculation() {
var trade = parseFloat(document.getElementById("trade").value);
var markup = parseFloat(document.getElementById("markup").value);
var price = parseFloat(document.getElementById("price").value);
var markupresult = price / trade;
var priceresult = markup * trade;
document.getElementById("markup").value = (markupresult).toFixed(2);
document.getElementById("price").value = (priceresult).toFixed(2);
}
<div class="form-group"><label>Trade</label><input type="number" id="trade" name="trade"></div>
<div class="form-group"><label>Price</label><input type="number" id="price" name="price"></div>
<div class="form-group"><label>Markup</label><input type="number" id="markup" name="markup"></div>
Check the below snippet.
You can use a switch to change only one/vice versa.
Instead of change, you can use keyup which would provide you realtime output, (Whenever the user enter a number, the result will be calculated and shown).
document.getElementById("trade").addEventListener("change", calculation);
document.getElementById("price").addEventListener("change", calculation);
document.getElementById("markup").addEventListener("change", calculation);
function calculation(event) {
var trade = parseFloat(document.getElementById("trade").value);
var markup = parseFloat(document.getElementById("markup").value);
var price = parseFloat(document.getElementById("price").value);
var markupResult = price / trade;
var priceResult = markup * trade;
switch (event.target.getAttribute("id")) {
case "markup":
document.getElementById("price").value = priceResult.toFixed(2);
break;
case "price":
document.getElementById("markup").value = markupResult.toFixed(2);
break;
}
}
<div class="form-group">
<label>Trade</label><input type="number" id="trade" name="trade" />
</div>
<div class="form-group">
<label>Price</label><input type="number" id="price" name="price" />
</div>
<div class="form-group">
<label>Markup</label><input type="number" id="markup" name="markup" />
</div>

Does anyone know how to make a start number and end number produce a unordered list of square roots?

I'm having trouble figuring out how to make this work. I need the StartNumber box to have a value of 0 and the EndNumber to be 12. When clicking ClickMe! it produces an unordered list of each square root 0-12.
function wasClicked() {
let firstBox = document.getElementById("startNumber");
console.log("firstBox is " + firstBox);
let startNumber = firstBox.Value;
let secondBox = document.getElementById("endNumber");
let endNumber = secondBox.value || 12;
let line = "";
for (let i = startNumber; i = endNUmber; i++) {
line += "<li>The square root of " + i + " is " + Math.sqrt(i).toFixed(3) + "</li>\n";
}
console.log(line);
}
function isANumber(x) {
return !isNaN(x);
}
<div>
<label>Start Number:</label>
<input type="text" id="startNumber" /><br>
</div>
<div>
<label>End Number:</label>
<input type="text" id="endNumber" /><br>
</div>
<div>
<button onclick="wasClicked()">Click Me!</button>
</div>
<div></div>
<h2>The list</h2>
<ul id="theList"></ul>
Your code has a number of problems.
Firstly, casing matters in JavaScript, so it's firstBox.value not firstBox.Value, and endNumber is a completely different name than endNUmber. Make sure you know the correct case of any built-in properties or methods and use consistent casing in your variable names.
Secondly your for-loop syntax is off. It should be something along the lines of
for (let i = start; i <= end; i++) ...
Also, the .value property of HTML <input> elements is a string so you need to convert it to a number if you want to treat is as a number. There are a few ways to do this, but for this example, I'll use Number.parseFloat.
Lastly, you'll want to render the result on the DOM in some way. Again, there are a few ways to do this, but the simplest is Element.innerHTML.
Putting this all together, you'll have something like this:
function wasClicked() {
let firstBox = document.getElementById("startNumber");
let startNumber = Number.parseFloat(firstBox.value);
let secondBox = document.getElementById("endNumber");
let endNumber = Number.parseFloat(secondBox.value);
let line = "";
for (let i = startNumber; i <= endNumber; i++) {
line += `<li>The square root of ${i} is ${Math.sqrt(i).toFixed(3)}</li>`;
}
document.getElementById("theList").innerHTML = line;
}
function isANumber(x) {
return !isNaN(x);
}
<div>
<label>Start Number:</label>
<input type="text" id="startNumber" /><br>
</div>
<div>
<label>End Number:</label>
<input type="text" id="endNumber" /><br>
</div>
<div>
<button onclick="wasClicked()">Click Me!</button>
</div>
<div></div>
<h2>The list</h2>
<ul id="theList"></ul>

JavaScript parseInt Conversion

I am trying to run a calculation that populates a text box based on an onblur event. For some reason, my result is showing a NaN. I am not used to JS so any help will be appreciated.
NOTE: I am most actively working on the last function - markupNumCheck() because once this function is working I can simply just apply it to the other two functions.
Here is the JS:
function unitToSales(){
var unitPrice = document.getElementById("inputCost");
var percentMarkup = document.getElementById("inputMarkup");
var salesPrice = document.getElementById("inputPrice");
parseInt(unitPrice.value);
parseInt(percentMarkup.value);
parseInt(salesPrice.value);
if(unitPrice.value != "" && percentMarkup.value != "" ){
salesPrice.value = (unitPrice * (1+percentMarkup));
}
}
function salesToUnit(){
var unitPrice = document.getElementById("inputCost");
var percentMarkup = document.getElementById("inputMarkup");
var salesPrice = document.getElementById("inputPrice");
parseInt(unitPrice.value);
parseInt(percentMarkup.value);
parseInt(salesPrice.value);
if(percentMarkup.value != "" && salesPrice.value != "" ){
unitPrice.value = parseInt(unitPrice * (1+percentMarkup));
}
}
function markupNumCheck(){
var unitPrice = document.getElementById("inputCost");
var percentMarkup = document.getElementById("inputMarkup");
var salesPrice = document.getElementById("inputPrice");
parseInt(unitPrice.value);
parseInt(percentMarkup.value);
parseInt(salesPrice.value);
if(unitPrice.value != "" && percentMarkup.value != "" ){
salesPrice.value = (unitPrice * (1+percentMarkup));
} else if (percentMarkup.value != "" && salesPrice.value != "" ){
unitPrice.value = (unitPrice * (1+percentMarkup));
}
}
And here is HTML where I call code:
NOTE: This obviously is a form, I did not copy the entire document because the rest is irrelevant.
<div class="form-row">
<div class="form-group col-md-3">
<div class="form-group">
<label for="inputCost">Unit Cost</label>
<input type="text" class="form-control" id="inputCost" name="inputCost" onblur="unitToSales()" value="">
</div>
</div>
<div class="form-group col-md-3">
<div class="form-group">
<label for="inputMarkup">Percent Markup</label>
<input type="text" class="form-control" id="inputMarkup" name="inputMarkup" onblur="markupNumCheck()">
</div>
</div>
<div class="form-group col-md-3">
<div class="form-group">
<label for="inputCost">Sales Price</label>
<input type="text" class="form-control" id="inputPrice" name="inputPrice" onblur="salesToUnit()">
</div>
</div>
<div class="form-group col-md-3">
<div class="form-group">
<label for="inputQuantity">Quantity</label>
<input type="text" class="form-control" id="inputQuantity" >
</div>
</div>
</div>
Thank you all again for any help that you may be able to give.
parseInt will return the parsed integer value. When you call parseInt(value) and don't assign the value to a variable, the parsed value is just discarded. You are using the variable unitPrice after as a number, but it actually holds a DOM element, that is why you get the NaN.
You can fix it by inlining the parseInt call in your expression:
salesPrice.value = (parseInt(unitPrice.value) * (1+parseInt(percentMarkup)));
You need to assign each of your variables to the parseInt result.
So for example you'd reuse the unitPrice variable and assign it to the parseInt result
var unitPrice = document.getElementById("inputCost");
unitPrice = parseInt(unitPrice);
I noticed that every time you tried to use parseInt that you don't save the result like so:
var resultInt = parseInt(SomeString);
So when you try to calculate your values together you get NaN because they still in string form.
If you look at this if-statement for example in salesToUnit():
if(percentMarkup.value != "" && salesPrice.value != "" ){
unitPrice.value = parseInt(unitPrice * (1+percentMarkup));
}
unitPrice and percentMarkup are not parsed as integers so you are adding 1 (an integer) to percentMarkup (a string) and then multiplying it to unitPrice(also a string) and THEN parsing the result giving you NaN and setting that to unitPrice.value.
I would like to add that the parseInt calls that happen in the beginning of salesToUnit() when would seem unnecessary since if theres no value in percentMarkup and SalesPrice and would be better let till once you do you check. I would flip it around like this and change salesToUnit() to something like this:
if(percentMarkup.value != "" && salesPrice.value != "" )
{
var salesPriceInt = parseInt(salesPrice.value);
var percentMarkupInt = parseInt(percentMarkup.value);
unitPrice.value = unitPriceInt * (1+percentMarkupInt);
}
Also incorporating the safeParseInt function mentioned by #Vitalii would help as well to be even safer!
I hope you find this useful!

Jquery keyup only working in Chrome?

I have a basic cost calculator that I want to automatically add values as numbers are entered into the text fields. This works perfect in Chrome, but for some reason only in chrome. My goal is to have the new math results show up after the dollar sign whenever a number is entered into the text field. I am getting no console errors and JS Hint/Lint both look good.
Any ideas why this is working in chrome, but no where else?
Here is a fiddle: http://jsfiddle.net/Egreg87/j7r4zte8/4/
window.onload = function() {
$('input').keyup(function(){ // run anytime the value changes
var duration = parseFloat($('#duration').val()) || 0; // get value of field
var timeHr = parseFloat($('#timeHr').val()) || 0; // get value of field
var distance = parseFloat($('#distance').val()) || 0; // get value of field
var flight = parseFloat($('#flight').val()) || 0; // convert it to a float
var parkDays = parseFloat($('#parkDays').val()) || 0;
var parking = '12.00';
var fuelCost= '3.50';
$('#added').html(flight + parkDays * parking + distance * (2) / (20) * fuelCost + timeHr); // add them and output it
});
$('input').keyup(function(){ // run anytime the value changes
var distance1 = parseFloat($('#distance1').val()) || 0; // get value of field
var flight1 = parseFloat($('#flight1').val()) || 0; // convert it to a float
var parkDays = parseFloat($('#parkDays').val()) || 0;
var parking1 = '12.00';
var fuelCost1= '3.50';
$('#added1').html(flight1 + parkDays * parking1 + distance1 * (2) / (20) * fuelCost1); // add them and output it
});
$('input').keyup(function(){ // run anytime the value changes
var duration2 = parseFloat($('#duration2').val()) || 0; // get value of field
var timeHr = parseFloat($('#timeHr').val()) || 0; // get value of field
var distance2 = parseFloat($('#distance2').val()) || 0; // get value of field
var flight2 = parseFloat($('#flight2').val()) || 0; // convert it to a float
var parkDays = parseFloat($('#parkDays').val()) || 0;
var parking2 = '12.00';
var fuelCost2= '3.50';
$('#added2').html(flight2 + parkDays * parking2 + distance2 * (2) / (20) * fuelCost2); // add them and output it
});
<!--Caclulator fields-->
<div id="calc-fields">
<div>
<label class="main3">MGM</label><br>
<label>Total Cost of Your Flight(s) from MGM $:</label>
<input name="numeric" class="allownumericwithdecimal" id="flight"></input><br />
<label for="distance">Distance (miles): </label>
<input type="text" class="number" name="distance" id="distance"></input>
<label for="duration">Drive Time (minutes): </label>
<input type="text" name="duration" id="duration" class="drive-time"></input>
<label class="main">Total Cost from MGM: <br>$</label>
<span id="added" class="main2"></span><br />
</div>
<div>
<label class="main3">ATL</label><br>
<label>Total Cost of Your Flight(s) from ATL $:</label>
<input name="numeric" class="allownumericwithdecimal" id="flight1"></input><br />
<label for="distance1">Distance (miles): </label>
<input type="text" name="distance1" id="distance1"></input>
<label for="duration1">Drive Time (minutes): </label>
<input type="text" name="duration1" id="duration1" class="drive-time"></input>
<label class="main">Total Cost from ATL:<br> $</label>
<span id="added1" class="main2"></span><br />
</div>
<div>
<label class="main3">BHM</label><br>
<label>Total Cost of Your Flight(s) from BHM $:</label>
<input name="numeric" class="allownumericwithdecimal" id="flight2"></input><br />
<label for="distance2">Distance (miles): </label>
<input type="text" name="distance2" id="distance2"></input>
<label for="duration">Drive Time (minutes):</label>
<input type="text" name="duration2" id="duration2" class="drive-time"></input>
<label class="main">Total Cost from BHM: <br>$</label>
<span id="added2" class="main2"></span><br />
</div>
<br>
<hr></hr>
<!--End calc fields-->
Couple of things- changed to document ready. You were defining a function calc1 as you were passing it as a call back, changed to anonymous function. In stead on .keyup changed to on('keyup')
If you take the time to look at console errors, things like this will never be an issue for you..
Below is fixed jsfiddle
http://jsfiddle.net/j7r4zte8/7/
$('input').on('keyup', function(){ //vs $('input').keyup(function calc1()

Categories

Resources