function to compute and input average speed - javascript

I have 3 input fields, distance, time and average speed. I would like the average speed field to be automatically computed to minimise user effort. As such I have come up with this function but it doesn't work:
$('#Avg Speed').click(function(event) {
var distance = $('#Distance');
var time = $('#Time');
var speed = distance / time;
$(this).append(speed);
});
Any ideas? Even better than clicking the field would be that the result automatically comes up once distance and time is completed. No doubt my code reveals what a novice I am at this stuff.

If your speed is auto generated is good to make it disabled if it's input.
Also may be best event you search for is blur
HTML part:
<label>Distance <input type="text" name="distance" id="distance"></label><br />
<label>Time <input type="text" name="time " id="time"></label><br />
<label>Speed <input type="text" name="speed " id="speed" disabled></label>
Jquery part:
$('#distance,#time').on('blur', function() {
var distance = $('#distance');
var time = $('#time');
var speed = $('#speed');
if(parseInt(time.val()) > 0 && parseInt(distance.val()) > 0)
speed.val(distance.val()/time.val());
})
Also if it will be good a idea to add measures for times, distance and speed

<input type="text" id="Distance">
<input type="text" id="Time">
<input type="text" id="Speed">
$('#Avg Speed').focus(function(event) {
var distance = $('#Distance').val();
var time = $('#Time').val();
var speed = distance / time;
$(this).val(speed);
});

try with an onKeyUp event, i'll give you an example:
HTML:
<input type="number" id="distance"></input>
<input type="number" id="speed"></input>
<input type="number" id="speed" onKeyUp="calcultate()"></input>
<Label id="result"></Label>
JS:
function calculate(){
//get all input values calculate your thing and then put it back //in the result, this will be called each time a user presses a key in the //last input field
$('#result').text(yourResult);
}

Related

Duplicated script not showing result

This is my first question here, so pardon the naiveness please, thx.
I am currently building a calculator based on HTML, JS (+jQuery) and CSS. My calculator is a multi-input calculator that can count various things on a single webpage. For context, the calculator that I am building at the moment, is a gear calculator. It supposed to be able to calculate various items using various formulas. For the first item, it will be capable to calculate the module of a gear. This first calculation was successful with the following script:
$(document).ready(function(){
$('input[type="text"]').keyup(function () {
var valZ = parseInt($('.jumlahGigi').val());
var valD = parseInt($('.diameterPitch').val());
var sum = valD/valZ;
$("input#resultModule").val(sum);
});
});
I duplicate the script to calculate other items but I don't forget to change the variables. This is the next script to calculate the amount of teeth on a gear:
$(document).ready(function(){
$('input[type="text"]').keyup(function () {
var valM = parseInt($('.module').val());
var valD = parseInt($('.diameterPitch').val());
var sum = valD/valM;
$("input#resultAot").val(sum);
});
});
and this is the last script I wrote to calculate the diameter pitch:
$(document).ready(function(){
$('input[type="text"]').keyup(function () {
var valM = parseInt($('.module').val());
var valZ = parseInt($('.jumlahGigi').val());
var sum = valZ*valM;
$("input#resultDP").val(sum);
});
});
For the first item calculation, when I enter a number onto the input form, the result came out successfully. But for the other 2 calculations, the result won't came out. Can anyone maybe spot where my flaw lies?
Your issue is that $('.class').val() will take the value only from the first matching element, essentially $('.class').first().val().
In your fiddle, you have 2 of each input: .module, .diameter, .jumlahGigi.
Your calculations are working fine, but they are taking values from earlier inputs - eg diameter pitch takes teeth from module and module from the teeth input.
The easiest option is to use unique classes for each input.
//module
$(document).ready(function() {
$('input[type="text"]').keyup(function() {
var valZ = parseInt($('.moduleJumlahGigi').val());
var valD = parseInt($('.moduleDiameterPitch').val());
var sum = valD / valZ;
$("input#resultModule").val(sum);
});
});
//Amount of teeth
$(document).ready(function() {
$('input[type="text"]').keyup(function() {
var valM = parseInt($('.aotModule').val());
var valD = parseInt($('.aotDiameterPitch').val());
var sum = valD / valM;
$("input#resultAot").val(sum);
});
});
//Diameter Pitch
$(document).ready(function() {
$('input[type="text"]').keyup(function() {
var valM = parseInt($('.diameterModule').val());
var valZ = parseInt($('.diameterJumlahGigi').val());
var sum = valZ * valM;
$("input#resultDP").val(sum);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div class="general">
<div class="module">
<label class="label"> Module </label>
<input type="text" class="moduleDiameterPitch" placeholder="Diameter Pitch">
<input type="text" class="moduleJumlahGigi" placeholder="Amount of Teeth">
<input type="text" disabled="disabled" id="resultModule" placeholder="Module">
</div>
<div class="AoT">
<label class="label"> Amount of Teeth </label>
<input type="text" class="aotDiameterPitch" placeholder="Diameter Pitch">
<input type="text" class="aotModule" placeholder="Module">
<input type="text" disabled="disabled" id="resultAot" placeholder="Amount of Teeth">
</div>
<div class="diameterPitch">
<label class="label">
Diameter Pitch
</label>
<input type="text" class="diameterJumlahGigi" placeholder="Amount of Teeth">
<input type="text" class="diameterModule" placeholder="Module">
<input type="text" placeholder="Diameter Pitch" disabled="disabled" id="resultDP">
</div>
</div>
The alternative is to use relative DOM navigation ($(this).closest(".calc").find(".module") - but as the calculations are very specific, it makes sense to name the inputs specifically for each calc.

How to convert Javascript numbers to a string and pass it to an input box

i'm stuck trying to convert feet to miles. here is my code so far:
function convertData() {
var distance = document.getElementById('distance').innerHTML;
var mile = 5280;
var result = distance /mile;
document.getElementById('distance').innerHTML = result;
};
and from the answer here, i'm trying to implement this to the
document.getElementById tag up in the beginning of the document found here..
<input type="button" value='Convert to Miles' onclick="convertData();">
<input id="distance" type="number" value=453454>
..so when a user clicks that button, the data gets converted.
this is the default line when a user opens a page on first try:
any advice or thoughts?
function convertData() {
var distance = document.getElementById('distance').value;
var mile = 5280;
var result = distance / mile;
document.getElementById('answer').innerHTML = +result;
};
<div id="answer"></div>
<input type="button" value='Convert to Miles' onclick="convertData();">
<input id="distance" type="number" value=453454>
I will recommend displaying the answer in another element, and leaving the input free for the user to make changes.
the simpliest way
html inputs with a type=number have the valueAsNumber property to directly process their numeric value.
(There is also a valueAsDate for those of type=date)
const
distance_el = document.getElementById('distance')
, mile = 5280
;
function convertData()
{
distance_el.valueAsNumber /= mile
}
<input type="button" value="Convert to Miles" onclick="convertData();">
<input id="distance" type="number" value="453454">
You should be getting/setting the input value property rather than the innerHTML.
The innerHTML property is used to return the HTML content of an element, while the value property is used to return the value of a text field.
function convertData() {
var distance = document.getElementById('distance').value;
var mile = 5280;
var result = distance / mile;
document.getElementById('distance').value = result;
};
<input type="button" value='Convert to Miles' onclick="convertData();">
<input id="distance" type="number" value=453454>
Simplified version:
function convertData(t) {
t.nextElementSibling.value = t.nextElementSibling.value/5280;
};
<input type="button" value='Convert to Miles' onclick="convertData(this);">
<input id="distance" type="number" value=453454>

Limit input to show only thousans in HTML or JS

I have an input filed where the user can enter some numbers. I want to limit the user to enter only thousands.
.
on the image, the user can enter other numbers even if the step is 1000.
onblur is executed when you lose the focus, so try this :
function autoThousand(){
var input = document.getElementById('thousand');
if (input.value%1000 !== 0 ){
input.value-=input.value%1000;
}
}
<input type="number" id="thousand" onblur="autoThousand();" step="1000">
This will round all number inputs to multiples of their step value, when they lose focus. It uses traditional rounding, where it rounds 1499 down to 1000 and 1500 up to 2000. (You can remove the commented line of code to always round down.)
This is one of those "add it and forget it" bits of code, where you just need to add inputs of type number, with a limit, and it will automatically round them all for you.
document.querySelectorAll("input[type=number][limit]").forEach(function(input) {
input.addEventListener("change", function() {
var value = parseInt(this.value, 10);
var limit = parseInt(this.getAttribute("limit"), 10);
value = value + (limit / 2); // remove this to always round down
this.value = value - (value % limit);
});
});
<input type="number" limit="1000" />(multiples of 1000)<br />
<input type="number" limit="100" />(multiples of 100)<br />
<input type="number" limit="500" />(multiples of 500)<br />
use this,
if you still want to make the field number field set the type="number" , step="1000", min="1000" max="any value of your choice"
<input type="text" name="quantity" id="num" onchange="checkInput()">
<script>
function checkInput(){
get_num = new Number(document.getElementById('num').value)
if(get_num < 1000){
document.getElementById('num').value = ""
alert("You must enter number in thousands")
}
}
</script>
Set 'max', 'min' and 'step' value.
<input type="number" name="points" step="1000" max="100000" min="1000">

Fields calculating only after a refresh

I apologize in advance for what I assume is a very basic question, but I am very new to scripting and would like to ask for some advice on a problem I am having.
Essentially I am creating a website that should sum the dollar amounts of two fields based on hours worked and return a total dollar amount. One of the fields has a fixed dollar amount and the other is a variable.
As far as I can tell the code should be working, but the field that should be user generated (esceptionalRate) seems to calculate correctly only after a page refresh, and then only on firefox... instead of automatically updating the total value when a change is made to the user field
code as follows:
<head>
</head>
<body>
<script>
$(document).ready(function () {
var standardRate = 110;
var exceptionalRate = $("#ex_rate").val();
var standardEntry = 0;
var exceptionalEntry = 0;
var totalVal = 0;
$("#Standard").on("change",function(){
standardEntry = $(this).val() * standardRate;
totalVal = standardEntry + exceptionalEntry;
$("#Amount").val(totalVal);
});
$("#Exceptional").on("change",function(){
exceptionalEntry = $(this).val() * exceptionalRate;
totalVal = standardEntry + exceptionalEntry ;
$("#Amount").val(totalVal);
});
</script>
and here's the HTML side:
<input name="Standard" type="number" step="any" value="0" id="Standard" size="10" />
<input type="text" size="10" name="ex_rate" id="ex_rate" />
<input name="Exceptional" type="number" step="any" value="0" id="Exceptional" size="10" />
<td valign="top" nowrap="nowrap"><font size="2">Total Amount Requested </font></td>
<td><input name="Amount" type="text" id="Amount" size="35"/></td>
thanks in advance for all your wisdom and knowledge.
You have forgotten to close the $(document).ready function
Try:
$(document).on("change", "#Standard", function(){
And:
$(document).on("change", "#Exceptional", function(){
The problem is that your exceptionalRate variable is out of the scope of your calculation, and only gets set to the initial value upon the page loading. You need to move it within the change handler:
$("#Exceptional").on("change",function(){
exceptionalRate = $("#ex_rate").val();
exceptionalEntry = $(this).val() * exceptionalRate;
totalVal = standardEntry + exceptionalEntry ;
$("#Amount").val(totalVal);
});

Calculating loan payment in Javascript

I am making a loan payment calculator on my website (www.kreditrunner.dk - In the bottom of the page).
EDIT: Problem solved with the following equation:
var princ = document.getElementById("amount").value;
var intr = document.getElementById("earlypercent").value/1200;
var term = document.getElementById("time").value;
document.getElementById("result").value = princ * intr / (1 - (Math.pow(1/(1 + intr), term)));
And also i used a keyup function instead. Cause when the key is pressed down, the input hasn't received the value yet, hence the wrong result :)
ORIGINAL POST:
I have my four inputs with respectively amount, interest rate per year in percent, payment period, and result.
<table>
<tr>
<td width="150">
<label for="amount">Lånebeløb (DKK)</label>
<input type="text" id="amount" name="amount" class="input-small">
<label for="earlypercent">ÅOP (%)</label>
<input type="text" id="earlypercent" name="earlypercent" class="input-small">
</td>
<td>
<label for="time">Løbetid (Mdr)</label>
<input type="text" id="time" name="time" class="input-small">
<label for="result"><b>Månedlig betaling (DKK)</b></label>
<input type="text" id="result" name="result" class="input-medium">
</td>
</tr>
</table>
For each of the first three input I have the listed calculations seen below which is derived from the following equation: http://www.wikihow.com/Calculate-a-Loan-Payment
$('#amount').keydown(function () {
var amount = document.getElementById("amount").value;
var earlypercent = document.getElementById("earlypercent").value;
var monthlypercent = earlypercent / 12 * 100;
var time = document.getElementById("time").value;
var negativetime = time * (-1);
var result = 1 + monthlypercent;
result = Math.pow(result, negativetime);
result = 1 - result;
result = monthlypercent / result;
document.getElementById("result").value = result * amount;
});
However, my result is weird as ****. As you can see when you try (e.g. with values, 1000, 10%, 12 months) the result is 8333.33 where it should have been around 83.33. Well actually it should be around 87.95.
So i could move the *100 in the montlypercent, however as you see when write an amount and tab to the next input field, the result changes even though the values are the same. Cant seem to get the equation right and the keydown function bothers me :/
Please help :)

Categories

Resources