JavaScript calculation won't print results - javascript

I have this code
$(function() {
if(document.getElementById('price') !== null && document.getElementById('dp') !== null){
var price = document.getElementById('price').value;
var deposite = document.getElementById('dp').value;
document.getElementById('remained').value = parseInt(price)-parseInt(deposite);
}
});
and this fields in my form
<div class="col-md-3">
<label for="price">Price *</label>
<input type="number" class="form-control" id="price" name="price">
</div>
<div class="col-md-3">
<label for="dp">DP *</label>
<input type="number" class="form-control" id="dp" name="dp">
</div>
<div class="col-md-3">
<label for="remained">Remained *</label>
<input type="number" class="form-control" id="remained" name="remained">
</div>
The logic is simple:
get price
get DP
print minus results in remained input
but somehow it doesn't print anything in remained input.
Any idea what I did wrong?

Your code is executing on page load and the value of the inputs are empty.
You should execute your code on some event like the following way:
$(function() {
$('#dp, #price').on('input', function(){
if(document.getElementById('price') !== null && document.getElementById('dp') !== null){
var price = document.getElementById('price').value;
var deposite = document.getElementById('dp').value;
document.getElementById('remained').value = parseInt(price)-parseInt(deposite);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-3">
<label for="price">Price *</label>
<input type="number" class="form-control" id="price" name="price">
</div>
<div class="col-md-3">
<label for="dp">DP *</label>
<input type="number" class="form-control" id="dp" name="dp">
</div>
<div class="col-md-3">
<label for="remained">Remained *</label>
<input type="number" class="form-control" id="remained" name="remained">
</div>

I think you should put the calculation to ready function
because it is asynchronous
$( document ).ready(function() {
console.log( "ready!" );
// calculation
});
Or better use angular ... Instead of jQuery

the calculation is right but it doen one time on page ready event
add manual button to tell javascrip when to calculate the value
alos add event listener to automatically call on change
<div class="col-md-3">
<label for="price">Price *</label>
<input type="number" class="form-control" id="price" name="price">
</div>
<div class="col-md-3">
<label for="dp">DP *</label>
<input type="number" class="form-control" id="dp" name="dp">
</div>
<div class="col-md-3">
<label for="remained">Remained *</label>
<input type="number" class="form-control" id="remained" name="remained">
</div>
<button type="button"
onclick="cal()">
cal
</button>
$(function() {
document.getElementById("price").addEventListener("change",cal);
document.getElementById("dp").addEventListener("change",cal);
});
function cal(){
if(document.getElementById('price') !== null && document.getElementById('dp') !== null){
var price = document.getElementById('price').value;
var deposite = document.getElementById('dp').value;
document.getElementById('remained').value = parseInt(price)-parseInt(deposite);
}
}

The js code runs on the initial loading of webpage. The js code must be called by an onclick or an onkeyup

Related

How to show total value of two text box in another box - Javascript

I am new to javascript, I want to get two fees in text boxes and show sum of those two fees in another text box (which is disabled, so can't edit it, just for showing purpose) below is my html form.. result should show when entering in fee1 or fee2 not in submit button. How to do it?
<div class="row">
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Consulation Fees:</b><span class="text-danger">*</span></label><input type="number" class="form-control" id="fee1" name="fee1" required min="0">
</div>
</div>
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Other Charges:</b></label><input type="number" class="form-control" id="fee2" name="fee2" min="0">
</div>
</div>
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Total Fee:</b></label><input type="number" disabled class="form-control" id ="total_fee" name="total_fee" >
</div>
</div>
use input event on fee1 and fee2 and then sum their values and put as value of total_fee.
e.g.
const fee1 = document.getElementById("fee1");
const fee2 = document.getElementById("fee2");
const total_fee = document.getElementById("total_fee");
fee1.addEventListener("input", sum);
fee2.addEventListener("input", sum);
function sum() {
total_fee.value = Number(fee1.value)+Number(fee2.value);
}
see in action
https://jsbin.com/lizunojadi/edit?html,js,output
Basically you listen to input event on both of the controls, summing the values into the other input.
document.querySelectorAll("#fee1, #fee2").forEach(function(elem) {
elem.addEventListener("input", do_sum)
})
function do_sum() {
var total = 0
document.querySelectorAll("#fee1, #fee2").forEach(function(elem) {
total += +elem.value;
})
document.querySelector("#total_fee").value = total
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" rel="stylesheet">
<div class="container">
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label class="gr"><b>Consulation Fees:</b><span class="text-danger">*</span></label><input type="number" class="form-control" id="fee1" name="fee1" required min="0">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label class="gr"><b>Other Charges:</b></label><input type="number" class="form-control" id="fee2" name="fee2" min="0">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label class="gr"><b>Total Fee:</b></label><input type="number" disabled class="form-control" id="total_fee" name="total_fee">
</div>
</div>
</div>
</div>
Here is the simple solution for your code,
<div class="row">
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Consulation Fees:</b><span class="text-danger">*</span></label><input type="number" class="form-control" id="fee1" name="fee1" required min="0" value="0">
</div>
</div>
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Other Charges:</b></label><input type="number" class="form-control" id="fee2" name="fee2" min="0" value="0">
</div>
</div>
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Total Fee:</b></label><input type="number" disabled class="form-control" id ="total_fee" name="total_fee" >
</div>
</div>
Here in the HTML code default value="0",
Now in Javascript,
const fee1 = document.getElementById('fee1');
const fee2 = document.getElementById('fee2');
const totalFee = document.getElementById('total_fee');
function doSum() {
const fee1Value = parseInt(fee1.value);
const fee2Value = parseInt(fee2.value);
const totalFeeValue = fee1Value + fee2Value;
totalFee.value = totalFeeValue;
}
fee1.addEventListener('input', doSum);
fee2.addEventListener('input', doSum);
doSum() function is executing oninput

Jquery onkeyup not working on boostrap modal. I'm using laravel blade template

I want to auto compute the extract fee, estimated value and num vehicle after I input a value in to tonnage.
I used a Bootstrap modal for this but as soon I put a value in tonnage it doesn't work. I'm confused right now.
$(document).ready(function() {
$('body').on('keyup', '#tonnage', function() {
var tonnage = $("#tonnage").val();
var num_vehicle;
if (tonnage <= 20) {
num_vehicle = 1;
$("#num_vehicle").val(num_vehicle);
} else {
num_vehicle = tonnage / 20;
$("#num_vehicle").val(num_vehicle);
}
var total_estimate_value = num_vehicle * 6000;
$("#estimated_value").val(total_estimate_value);
var total_extraction_fee = num_vehicle * 6000 * 0.1;
$("#extraction_fee").val(total_extraction_fee);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="col-md-6">
<label for="inputCity" class="form-label">Volume/Tonnage</label>
<input type="text" class="form-control" id="tonnage" name="tonnage">
</div>
<div class="col-md-6">
<label for="inputCity" class="form-label">Extraction Fee</label>
<input type="text" class="form-control" id="extraction_fee" name="extraction_fee" readonly="">
</div>
<div class="col-md-6">
<label for="inputCity" class="form-label">Estimated Value</label>
<input type="text" class="form-control" id="estimated_value" name="estimated_value" readonly="">
</div>
<div class="col-md-6">
<label for="inputCity" class="form-label">No. of Vehicle</label>
<input type="text" class="form-control" id="num_vehicle" name="num_vehicle" readonly="">
</div>
The main issue is because you don't round the result of tonnage / 20, so you get a fraction of a vehicle, eg. 21 tons = 1.05 vehicles, instead of found up to the nearest integer, eg. 21 tons = 2 vehicles. This can be achieved using Match.ceil().
Also, be careful of implicit type conversions from string to int/floats. It's better to be explicit with this, as in the following example:
jQuery($ => {
$(document).on('keyup', '#tonnage', function() {
var tonnage = parseFloat($(this).val());
var numberOfVehicles = Math.ceil(tonnage / 20);
$('#num_vehicle').val(numberOfVehicles);
var total_estimate_value = numberOfVehicles * 6000;
$("#estimated_value").val(total_estimate_value);
var total_extraction_fee = numberOfVehicles * 6000 * 0.1;
$("#extraction_fee").val(total_extraction_fee);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="col-md-6">
<label for="inputCity" class="form-label">Volume/Tonnage</label>
<input type="text" class="form-control" id="tonnage" name="tonnage">
</div>
<div class="col-md-6">
<label for="inputCity" class="form-label">Extraction Fee</label>
<input type="text" class="form-control" id="extraction_fee" name="extraction_fee" readonly="">
</div>
<div class="col-md-6">
<label for="inputCity" class="form-label">Estimated Value</label>
<input type="text" class="form-control" id="estimated_value" name="estimated_value" readonly="">
</div>
<div class="col-md-6">
<label for="inputCity" class="form-label">No. of Vehicle</label>
<input type="text" class="form-control" id="num_vehicle" name="num_vehicle" readonly="">
</div>

how to auto calculate fields in inputs?

I am trying to auto calculate the discount amount by filling in two input fields but I don't know what am I doing wrong. What I want is that as I fill both inputs it appears the result in a third input.
<div class="form-group col-md-2">
<label for="sale_price">Precio de Venta</label>
<input type="number" pattern="[0-9]+([\.,][0-9]+)?" step="00.01" name="sale_price" class="form-control" id="saleP" onkeyup="discount();">
</div>
<div class="form-group col-md-3">
<label for="discount_percentage">Porcentaje de descuento (%)</label>
<input type="number" name="discount_percentage" class="form-control" id="discountP" onkeyup="discount();">
</div>
<div class="form-group col-md-3">
<label for="discount">Descuento</label>
<input type="number" name="discount" placeholder="discount" class="form-control">
</div>
<script type="text/javascript">
function discount() {
var x;
(document.getElementById('saleP').document.getElementById('discountP')) / 100 = x
}
</script>
Does anyone knows what I am doing wrong?
Not sure what your thought was behind the example line.
I've made the following changes:
Added an id to the last input to target it
<input id="discount">
Get price input
const price = document.getElementById('saleP').value;
Get percentage value
const percentage = document.getElementById('discountP').value;
Calculate discount
const discount = price / 100 * percentage;
Set to last input
document.getElementById('discount').value = discount;
function discount(){
const price = document.getElementById('saleP').value;
const percentage = document.getElementById('discountP').value;
const discount = price / 100 * percentage;
document.getElementById('discount').value = discount;
}
<div class="form-group col-md-2">
<label for="sale_price">Precio de Venta</label>
<input type="number" pattern="[0-9]+([\.,][0-9]+)?" step="00.01" name="sale_price" class="form-control" id="saleP" onkeyup="discount();">
</div>
<div class="form-group col-md-3">
<label for="discount_percentage">Porcentaje de descuento (%)</label>
<input type="number" name="discount_percentage" class="form-control" id="discountP" onkeyup="discount();">
</div>
<div class="form-group col-md-3">
<label for="discount">Descuento</label>
<input type="number" name="discount" placeholder="discount" id="discount" class="form-control" >
</div>
Well you are not inputting variable x value into anything . If you add onchange event also, than it will work if user uses to increase decrease value using buttons.
Instead of adding two events you can add oninput for dynamic changes whether user input values using keyboard or buttons
function discount() {
var buyActualPrice = document.getElementById('saleP').value
var cardDisc = document.getElementById('discountP').value
var buyAtDiscAmount = (buyActualPrice * cardDisc) / 100
document.getElementById('DiscountAmount').value = buyAtDiscAmount
var priceAfterDisc = buyActualPrice - buyAtDiscAmount
document.getElementById('PriceAfterDisc').innerHTML = priceAfterDisc
}
document.querySelectorAll("#DiscountAmount").forEach(discount)
<div class="form-group col-md-2">
<label for="sale_price">Price</label>
<input type="number" pattern="[0-9]+([\.,][0-9]+)?" step="00.01" name="sale_price" class="form-control" id="saleP" oninput="discount();">
</div>
<div class="form-group col-md-3">
<label for="discount_percentage">Percentage disc. (%)</label>
<input type="number" name="discount_percentage" class="form-control" id="discountP" oninput="discount();">
</div>
<div class="form-group col-md-3">
<label for="discount">Discount Amount</label>
<input type="number" name="discount" placeholder="discount" class="form-control" id="DiscountAmount">
</div>
<div>Price after discount applied : <span id="PriceAfterDisc"></span></div>
The last line in JavaScript is added so that if there are initial values than the results are shown at the start before any event

Addition, Subtraction and Division simultaneously on JavaScript

I have this text box:
<div class="form-group">
<label>Enter Sum of Cleared</label>
<input type="text" name="sum_cleared" id="sum_cleared" class="form-control" />
</div>
I want to divide sum_cleared by 0.85 then multiply the result by 0.94 and subtract it from the original value that is typed in sum_cleared and show the final result in:
<div class="form-group">
<label>Sum of Total</label>
<input type="text" name="sum_total" id="sum_total" class="form-control total" readonly/>
</div>
I want to do this dynamically using the onchange and oninput events so it updates the value of sum_total as the user types the value on sum_cleared.
What is the easiest way to accomplish this?
Thank you so much
I was able to do it doing the following:
<div class="form-group">
<label>Enter Sum of Cleared</label>
<input type="text" name="sum_cleared" id="sum_cleared"
class="form-control"
oninput="GetTotal(this.value)" onchange="GetTotal(this.value)"/>
</div>
<div class="form-group">
<label>Total Commission</label>
<input type="text" name="sum_total" id="sum_total"
class="form-control total" readonly/>
</div>
Then adding a small script:
<script type="text/javascript">
function GetTotal(valNum) {
document.getElementById("sum_total").value=valNum/0.85*0.94-valNum
}
</script>
you can do like:
const input = document.querySelector('#sum_cleared');
const output = document.querySelector('#sum_total');
input.addEventListener('input', update);
input.addEventListener('change', update);
function update() {
const updated = input.value - ((input.value / 0.85) * 0.94);
output.value = updated;
}
<div class="form-group">
<label>Enter Sum of Cleared</label>
<input type="text" name="sum_cleared" id="sum_cleared" class="form-control" />
</div>
<div class="form-group">
<label>Sum of Total</label>
<input type="text" name="sum_total" id="sum_total" class="form-control total" readonly/>
</div>

Issue With JavaScript / HTML Form Validation

The method validateRegistrationForm is not being called, I have tested this by placing an alert inside and can't figure out why this is the case.
There is other JavaScript to validate other things though I have removed that until this issue is resolved.
The JavaScript itself is being linked to the HTML via script tags inside of the body. I put an alert at the top of the JS to make sure the link is working and it is.
HTML:
<form name="registrationForm" id="registrationForm" action="AddUserDetails">
<div class="form-group">
<label for="firstName">First Name</label>
<span id="firstNameError">*</span>
<input type="text" class="form-control" id="firstName">
</div>
<div class="form-group">
<label for="lastName">Second Name</label>
<span id="lastNameError">*</span>
<input type="text" class="form-control" id="lastName">
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number</label>
<span id="phoneNumberError">*</span>
<input type="text" class="form-control" id="phoneNumber">
</div>
<div class="form-group">
<label for="eMail">E-Mail</label>
<span id="eMailError">*</span>
<input type="text" class="form-control" id="eMail">
</div>
<div class="form-group">
<label for="eMailConfirmation">Confirm E-Mail</label>
<span id="eMailConfirmationError">*</span>
<input type="text" class="form-control" id="eMailConfirmation">
</div>
<div class="form-group">
<label for="password">Password</label>
<span id="passwordError">*</span>
<input type="password" class="form-control" id="password">
</div>
</form>
<div class="text-center">
<input type="button" id="submitRegistationForm" value="Submit">
</div>
JavaScript:
var $ = function (id) {
return document.getElementById(id);
}
var validateRegistrationForm = function () {
alert("");
var isValid = true;
//First Name Validation
if ($("firstName").value == "") {
$("firstNameError").firstChild.nodeValue = "This Text Box Cannot Be Blank";
isValid = false;
} else {
$("firstNameError").firstChild.nodeValue = "";
}
//Second Name Validation
if ($("lastName").value == "") {
$("lastNameError").firstChild.nodeValue = "This Text Box Cannot Be Blank";
isValid = false;
} else {
$("lastNameError").firstChild.nodeValue = "";
}
if (isValid) {
$("registrationForm").submit();
}
}
window.onload = function () {
$("submitRegistationForm").onclick = validateRegistrationForm;
}
Redefining $ seems like an awful idea, especially if this is code shared amongst other developers. In either case, why even wait for window.onload? You could just declare your click handler outside of it. Working jsfiddle:
$("submitRegistationForm").onclick = validateRegistrationForm;
https://jsfiddle.net/ou3gLLqe/

Categories