Fields calculating only after a refresh - javascript

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

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.

I cannot connect javascript function with html <input> tags and onclick doesn't work

Hi I am working on a website and i stumbbled across an annoying thing. I cannot, for the love of anything, get to work my form to be able to do some maths and insert them into tag.
P.S nothing works for me, even GetElementsById... or other callouts :(
<script type="text/javascript">
function price(this.form){
var amount = form.elements[1].value;
var gold_price = 0.17;
var price_calc = 0;
price_calc = (amount/gold_price) + " M";
window.alert("price_calc");
form.elements[5].value = price_calc;
}
</script>
//this is input that i would like to get a number to work with in the function
<div>
<input type="text" id="amount" value="10" onchange="price(this.form)" onclick="price(this.form)" maxlength="4" required/>
</div>
//this is input I would like to write in in after function is done functioning :)
<input type="text" id="total_price" placeholder="Total:"/>
thanks for any help in advance.
thanks again,...
Declare your price function to receive an input parameter. Actually this.form as parameter is an invalid statement and leads to an error.
Instead pass this (inside your on* property) and select the input value.
// select #total_price
const totalPrice = document.getElementById( 'total_price' );
function price( input ) {
// Convert value to a number
var amount = +input.value;
var gold_price = 0.17;
var price_calc = 0;
price_calc = ( amount / gold_price ) + " M";
totalPrice.value = price_calc;
}
<input type="text" id="amount" value="10" oninput="price( this )" onclick="price( this )" maxlength="4" required/>
<br>
<input type="text" id="total_price" placeholder="Total:" />
This code working:
<input type="text" value="10" oninput="price(this)" maxlength="4" />
<input type="text" id="total_price" placeholder="Total:" />
<script>
function price(el){
var amount = parseInt(el.value);
var gold_price = 0.17;
var price_calc = (amount / gold_price) + " M";
window.alert("Total: " + price_calc);
document.getElementById('total_price').value = "Total: " + price_calc;
}
</script>

function to compute and input average speed

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

Update two <outputs> from a range slider

Grateful for help updating two different values from a range slider and a hidden field value.
This currently updates the fee output perfectly and shows the total output before any slider value change but when the slider is users the second output shows ie. "undefined300" where 300 is the slider value. It is not adding the hidden field value basically. Sure I'm doing something stupid.
<input type="range" min="0" max="100" value="50" id="fee" step="1" oninput="outputUpdate(value)">
<input type="hidden" id="subTotal" value="1000" />
$<output for="fee" id="fee"> </output>
$<output for="fee subTotal" id="total"> </output>
<script>
function outputUpdate(fee, subTotal) {
document.querySelector('#fee').value = fee;
document.querySelector('#subTotal').value = subTotal;
var total = +subTotal + +fee
document.querySelector('#total').value = total;
}
</script>
You are calling outputUpdate(value) but your function takes two parameters as it is outputUpdate(fee, subTotal){ ... }, so subTotal will be "undefined". There are other problems too.
Try this updated script:
<script>
function outputUpdate(fee) {
document.querySelector('#fee').value = fee;
var subTotal = document.querySelector('#subTotal').value;
var total = parseInt(subTotal) + parseInt(fee);
document.querySelector('#total').value = total;
}
</script>
Demo: http://jsbin.com/pudequ/1/

JavaScript function Not Working with onchange attribute of input tag

I have been trying to replicate Duncan Donut Example from HEAD FIRST JAVASCRIPT, but the function subTotal() is never triggered by onchange event and when I look into HTML REFERENCE, I did not find any onchange event in list provided.
Duncan.html
<html>
<head><title>Duncan Online Donut's Service</title></head>
<script type="text/javascript">
function subTotal(){
document.write("working");
const TAXRATE = 0.095;
const DONUTRATE = 0.5;
var tax = 0;
var subTotal = 0;
var total = 0;
var cakedonut = parseInt(document.getElementById("cakedonut").value);
var glazedonut = parseInt(document.getElementById("glazedonut").value);
if(isNaN(cakedonut))
cakedonut = 0;
if(isNaN(glazedonut))
glazedounut = 0;
subTotal = (cakedonut + glazedonut)* DONUTRATE ;
tax = subTotal * TAXRATE ;
total = subTotal + tax ;
document.getElementById("subTotal").value = "$" + subTotal.toFixed(2);
document.getElementById("tax").value = "$" + tax.toFixed(2);
document.getElementById("total").value = "$" + total.toFixed(2);
}
</script>
<body>
<h1><b><i>Duncan Online Donut's Service</i></b></h1>
<form>
Name : <input id="name" type="text" name="name"/><br><br>
#no of cake donuts : <input id="cakedonut" type="text" name="cakedonut" onchange="subTotal()"/><br><br>
#no of glazed donuts : <input id="glazedonut" type="text" name="glazedonut" onchange="subTotal("/><br><br>
subTotal : <input id="subTotal" type="text" name="subTotal" /><br><br>
tax : <input id="tax" type="text" name="tax" /><br><br>
Total : <input id="total" type="text" name="total"/><br><br>
<input type="submit"/><br><br>
</form>
</body>
</html>
JSFiddle
The above is my code. I tried running this on IE and Chrome but in vain. Thanks in advance.
The problem is you have defined a variable and a function both with the same name subTotal and the variable declaration is overriding the function definition. Change the function name to anything say subTotal1 it will work.
JSBIN link
change your function name. don't use subTotal(); and don't use document.write("working");
function subTotalnew()
{
alert('working');
}
onchange="subTotalnew() it gonna be work after input blur.
oninput="subTotalnew() it gonna be work when input entering something.

Categories

Resources