cash denomination calculator - javascript

I've created cash denomination calculator in jquery, and it's working fine once you add entry but suppose if you try to change those entries then it's not calculating values as i expected.
Just fill those values and you'll get total of all, but if try to change the value of input box inside div with '.mul_by' class[i.e. the small input box before '=' sign] then it's not calculating the total properly.
And here's the jsFiddle for the same.
$('.mul_by').each(function (i) {
var _this = $(this),
//set default input value to zero inside .mul-by div
setZero = _this.find('.form-control').val(0),
//set default input value to zero inside .mul-val div
setDenominationVal = _this.siblings('.mul_val').find('.form-control').val(0),
//set default input value to zero inside .total div
setTotalVal = $('.total').val(0);
setZero.on('change', function () {
//watch and store input val. inside .mul_by
var getUpdatedVal = _this.find('.form-control').val(),
//get label text
getDenominationVal = parseInt(_this.siblings('label').text()),
//update mul_by div after multiplication
updateDenominationVal = _this.siblings('.mul_val').find('.form-control');
if (getUpdatedVal > 0) {
var vals = updateDenominationVal.val(getUpdatedVal * getDenominationVal);
total = parseInt(setTotalVal.val()) + parseInt(vals.val());
setTotalVal.val(total);
} else {
updateDenominationVal.val(0);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-2 col-xs-2" for="batch">2000</label>
<div class="col-md-1 col-xs-4 mul_by">
<span>x </span> <input type="text" class="form-control">
</div>
<div class="col-md-3 col-xs-5 mul_val">
<span style="font-size: 18px;">= </span> <input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2 col-xs-2" for="batch">500</label>
<div class="col-md-1 col-xs-4 mul_by">
<span>x </span> <input type="text" class="form-control">
</div>
<div class="col-md-3 col-xs-5 mul_val">
<span style="font-size: 18px;">= </span> <input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2 col-xs-2" for="batch">100</label>
<div class="col-md-1 col-xs-4 mul_by">
<span>x </span> <input type="text" class="form-control">
</div>
<div class="col-md-3 col-xs-5 mul_val">
<span style="font-size: 18px;">= </span> <input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<hr>
<label class="control-label col-md-2 col-xs-2" for="batch">total:</label>
<div class="col-md-3 col-xs-5 mul_val">
<span style="font-size: 18px;">= </span> <input type="text" class="form-control total">
</div>
</div>
</form>
How do i update total after making changes?
Hope you understand it. Thanks in advance for your help.

Please check this code i get proper result I had made lot of changes at end hope you will get desired result:-
$(document).ready(function () {
$('.mul_by').each(function (i) {
var _this = $(this),
//set default input value to zero inside .mul-by div
setZero = _this.find('.form-control').val(0),
//set default input value to zero inside .mul-val div
setDenominationVal = _this.siblings('.mul_val').find('.form-control').val(0);
//set default input value to zero inside .total div
setTotalVal = $('.total').val(0);
setZero.on('change', function () {
var getcurrentval = $(this).val();
console.log('getcurrentval',getcurrentval)
//watch and store input val. inside .mul_by
var getUpdatedVal = _this.find('.form-control').val(),
//get label text
getDenominationVal = parseInt(_this.siblings('label').text()),
//update mul_by div after multiplication
updateDenominationVal = _this.siblings('.mul_val').find('.form-control');
console.log(getUpdatedVal,getDenominationVal)
var vals = 0,total=0;
if(getUpdatedVal > 0){
if(updateDenominationVal.val()>0){
vals = updateDenominationVal.val(getUpdatedVal * getDenominationVal - updateDenominationVal.val());
total = parseInt(setTotalVal.val()) + parseInt(vals.val()) ;
updateDenominationVal.val(getUpdatedVal * getDenominationVal);
console.log('total',total,'setTotal',setTotalVal.val(),vals.val());
}
else{
vals = updateDenominationVal.val(getUpdatedVal * getDenominationVal);
updateDenominationVal.val(getUpdatedVal * getDenominationVal);
total = parseInt(setTotalVal.val()) + parseInt(vals.val());
}
console.log(vals.val());
setTotalVal.val(total);
} else{
updateDenominationVal.val(0);
}
});
});
});

Related

How to change my add input field where if a new input field pop up a minus show?

i would like help for some improvement i would like to change the structure of my html this is the image below
I would like that when user press the plus a new input box however the right side there is a minus instead and if press minus the input box be gone
Example of image below
currently what i have is on my code is just like this
So how can i change it to be like the example of the image?
$('.add').on('click', add);
$('.remove').on('click', remove);
function add() {
var new_chq_no = parseInt($('#total_chq').val()) + 1;
var new_input = "<div style='margin-bottom:5px;'><input type='text' id='new_" + new_chq_no + "'pattern='^[0-9]{8}$' class='form-control col-9' required><div class='invalid-feedback'>Enter a correct PhoneNumber!</div></div>";
$('#new_chq').append(new_input);
$('#total_chq').val(new_chq_no);
}
function remove() {
var last_chq_no = $('#total_chq').val();
if (last_chq_no > 1) {
$('#new_' + last_chq_no).remove();
$('#total_chq').val(last_chq_no - 1);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="form-group row">
<label for="validationNumber" class="col-2 col-form-label">Contact:</label>
<div class="col-4">
<div class="flex" style="margin-bottom:5px;">
<input style="margin-right: 19px;" id="validationNumber" name="phonenumber" type="text" class="form-control" pattern="\b\d{8}\b" required>
<a onclick="add()"><label style="cursor: pointer; padding-top: 5px;"><i data-feather="plus">+</i></label></a>
<a onclick="remove()"><label style="cursor: pointer; padding-top: 5px;"><i data-feather="minus">-</i></label></a>
</div>
<div id="new_chq"> </div>
<input type="hidden" value="1" id="total_chq">
<div class="invalid-feedback">
Enter a correct PhoneNumber!
</div>
</div>
</div>
Here is a version that is using clone and delegation
Wrap the set in a container of their own
Wrap the containers in a container
Check that the user cannot delete the last row
Clone the number including the possible error message
No need for ID, you can navigate using closest and the name
const $container = $('#contactContainer')
$(".remove").eq(0).hide()
$container.on('click', ".ar", function(e) {
const add = $(this).is(".add");
const $phones = $container.find(".phone");
const len = $phones.length;
if (add) {
const $newPhone = $phones.eq(0).clone(true)
$newPhone.find("[name=phonenumber]")
.attr("id", `new_${$phones.length}`)
.val("");
$container.append($newPhone);
$newPhone.find(".add").hide(); // if you only want one plus
$newPhone.find(".remove").show()
} else {
$(this).closest(".phone").remove()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="form-group row">
<label class="col-2 col-form-label">Contact:</label>
<div class="col-4" id="contactContainer">
<div class="flex phone" style="margin-bottom:5px;">
<input style="margin-right: 19px;" name="phonenumber" type="text" class="form-control" pattern="\b\d{8}\b" required>
<span class="ar add"><label style="cursor: pointer; padding-top: 5px;"><i data-feather="plus">+</i></label></span>
<span class="ar remove"><label style="cursor: pointer; padding-top: 5px;"><i data-feather="minus">-</i></label></span>
<div class="invalid-feedback">
Enter a correct PhoneNumber!
</div>
</div>
</div>
</div>

Hide empty inputs in a dynamic form

When I am returning the dynamic form, I intend to hide the inputs when it returns an empty or null value.
For example, how can you retron the lines:
Id = 1 NumCap = 1 Capitulo = teste
Id = 2 NumCap = Capitulo =
Id = 3 NumCap = 2 Capitulo = teste1
When returning the form, when returning the line with Id = 2, hide the two inputs, because they come empty.
I return the form as follows:
success:function(data1){
var linha1 = ``;
for (var i = 0; i < data1.length; i++) {
Id = data1[i][0];
NumCap = data1[i][14];
Capitulo = data1[i][15];
linha1 += `<div class="teste1">
<div class="form-group col-md-2 testeeeee">
<input type="text" class="form-control1 alinha" name="Capitul[]" value="${NumCap}">
<span class="form-highlight"></span>
<span class="form-bar"></span>
<label class="label3" for="Capitulo">Nº Capitulo</label>
</div>
<div class="form-group col-md-4 testeeeee">
<input type="text" class="form-control1" name="Capitul1[]" value="${Capitulo}">
<span class="form-highlight"></span>
<span class="form-bar"></span>
<label class="label1" for="Capitulo">Capitulo</label>
</div>
</div>
}
I am trying to put this code before starting the form return:
if(!NumCap && !Capitulo){
$('.testeeeee').show();
}else{
$('.testeeeee').hide();
}
But it does not work.
success:function(data1){
var linha1 = ``;
Object.keys(data1).forEach(i=>{
Id = data1[i][0];
NumCap = data1[i][14];
Capitulo = data1[i][15];
if(!Id.length||!NumCap.length||!Capitulo.length){return;} //if any length of these values are 0, don't put them into linha1
linha1 += `<div class="teste1">
<div class="form-group col-md-2 testeeeee">
<input type="text" class="form-control1 alinha" name="Capitul[]" value="${NumCap}">
<span class="form-highlight"></span>
<span class="form-bar"></span>
<label class="label3" for="Capitulo">Nº Capitulo</label>
</div>
<div class="form-group col-md-4 testeeeee">
<input type="text" class="form-control1" name="Capitul1[]" value="${Capitulo}">
<span class="form-highlight"></span>
<span class="form-bar"></span>
<label class="label1" for="Capitulo">Capitulo</label>
</div>
</div>`
})
}
You can use this to check blank value and hide the textbox
if(jQuery(".testeeeee > .form-control1").length > 0){
$(".testeeeee > .form-control1").each(function(){
if($(this).val() == ''){
$(this).hide();
}else{
console.log("TEXTBOX IS NOT EMPTY \t \n");
$(this).show();
}
});
}
let me know if this helps you.

JS - Calculate price depending on span/div fields

I have a form, where a user can select between different options inside a few dropdown fields. Depending on the user selection, the values will be displayed inside a span field next to the dropdown field.
Now I would like to count all those values inside the span fields, so that I can display a total amount at the end of the form before it will be submitted.
Here is a part of my form:
<form name='formname_form' action='./index.php' method='post' class='formname-form' id='formname-form'>
<div class="row" id='save_prices'>
<div class="col-lg-8 offset-lg-2 col-md-10 offset-md-1 col-sm-12">
<div class="form-inline">
<label class="form-icon">
<figure>
<img src="../assets/images/symbol-1.png" alt="/">
</figure>
</label>
<div class="form-group">
<select name="field_a" id="field_a" onchange="CalcDiscount()">
<option value="0,00">Option A?</option>
<option value="6,17">Yes</option>
<option value="0,00">No</option>
</select>
</div>
<div class="amount-wrap-3">
<span>€ <span id='field_a_price' class='prices'></span></span>
</div>
</div>
<div class="form-inline">
<label class="form-icon">
<figure>
<img src="../assets/images/symbol-2.png" alt="/">
</figure>
</label>
<div class="form-group">
<select name="field_b" id="field_b" onchange="CalcDiscount()">
<option value="0,00">Option B</option>
<option value="17,50">Yes</option>
<option value="0,00">No</option>
</select>
</div>
<div class="amount-wrap-3">
<span>€ <span id='field_b_price' class='prices'></span></span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-8 offset-lg-2 col-md-10 offset-md-1 col-sm-12">
<div class="total-amount">
Total Price
<div class='price'><span id='total_price' class="total_price"></span> €</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-xs-12">
<div class="form-inline">
<input name='submit' type='submit' id='submit' value='Save' class='btn btn-form-indiv'/>
</div>
</div>
</div>
</form>
And here is my javascript part:
<script>
// Get references to the objects you need (<select> and <span>)
var field_a = document.getElementById('field_a');
var field_a_price = document.getElementById('field_a_price');
var field_b = document.getElementById('field_b');
var field_b_price = document.getElementById('field_b_price');
// When the list value changes, set the innerHTML of the <span>
field_a.onchange = function() {
field_a_price.innerHTML = this.value;
};
field_b.onchange = function() {
field_b_price.innerHTML = this.value;
};
var priceList = $('#save_prices').find('.prices');
var totalPrice = 0;
$.each(priceList, function(i, price){
totalPrice += parseInt($(price).text())
});
$('.total_price').text(totalPrice);
</script>
Does anyone have an idea what I am doing wrong? The value inside my span with the class total_price stays always 0. I assume that is has something to do with my onChange methods that I am using?
Problem
The total from the 2 select boxes are not appearing in the Total Price area.
Solution
Create a function and call it to fire off on the onchange event when a new value is selected in the selection boxes.
Example
// Get references to the objects you need (<select> and <span>)
var field_a = document.getElementById('field_a');
var field_a_price = document.getElementById('field_a_price');
var field_b = document.getElementById('field_b');
var field_b_price = document.getElementById('field_b_price');
// When the list value changes, set the innerHTML of the <span>
field_a.onchange = function() {
field_a_price.innerHTML = this.value;
// Calling new function
updateTotal();
};
field_b.onchange = function() {
field_b_price.innerHTML = this.value;
// Calling new function
updateTotal();
};
// New function
function updateTotal() {
var p = $('.prices').map(function () { return $(this).text(); }).get();
var totalPrice = 0;
$.each(p, function( index, value ) {
totalPrice = totalPrice + value;
$('.total_price').text(totalPrice);
});
}
Summary
I am not sure what you are attempting to do with the values considering they have commas.
To directly address your question, when your code is ran the reason the values are always empty is because all the code only runs on page load. When you change the selection box values only the code in the onchange was being ran. By adding a function that is called each time a selection is made we can populate the array from the class list returned with JQuery.

how to send the html form value in js page to use in another function

I'm trying to send the value of GST to order.js file if and only if the value of VAT mode is selected to be "with Vat" form the page new_order.php
<div class="form-group row">
<label for="vat" class="col-sm-3 col-form-label" onChange="getVatMode(this.value);" align="right">VAT Mode</label>
<div class="col-sm-6">
<select name="vatMode" value="data" class="form-control" id="vatMode" required="required">
<option value="1">Without VAT</option>
<option value="2">With VAT</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="gst" class="col-sm-3 col-form-label" align="right">GST (13%)</label>
<div class="col-sm-6">
<input type="text" readonly name="gst" class="form-control form-control-sm" id="gst" required/>
</div>
</div>
and I need to pass this value of VAT to be passed to order.js page without loading for calculation of sum
function calculate(dis,paid){
var sub_total = 0;
var gst = 0;
var net_total = 0;
var discount = dis;
var paid_amt = paid;
var due = 0;
$(".amt").each(function(){
sub_total = sub_total + ($(this).html() * 1);
})
gst = Math.round(0.13 * sub_total);
net_total = gst + sub_total;
net_total = net_total - discount;
due = net_total - paid_amt;
$("#gst").val(gst);
$("#sub_total").val(sub_total);
$("#discount").val(discount);
$("#net_total").val(net_total);
//$("#paid")
$("#due").val(due);
With Jquery you can use $("#YourFormId").serialize():
$("form").on( "submit", function( event ) {
event.preventDefault();
console.log($(this).serialize());
});
For a form element's value to be included in the serialized string, the element must have a name attribute
https://api.jquery.com/serialize/

How to set radio buttons values based on dropdown selection?

I want to set radio buttons values based on drop-down selection,Lets assume i have three values in drop-down(A,B and C) , If A or B is selected i want to set radio button default value to Summary and if C is selected i want set value to Detailed. Also when A & B is selected i want to make it non-editable..
Please help this is first time i am using radios with AngularJS.
main.html
<div class="row">
<div class="form-group col-md-6 fieldHeight">
<label for="cycleName" class="col-md-6 required">Scope Type :</label>
<div class="col-md-6">
<select kendo-drop-down-list k-data-text-field="'text'"
k-option-label="'Select'" k-data-value-field="'id'"
k-data-source="assessmentTypeOptions" name="assessmentType"
required ng-model="riskAssessmentDTO.scopeType" id="assessmentType"
maxlength="256" ng-change="assessmentType()"></select>
<p class="text-danger"
ng-show="addAssessment.assessmentType.$touched && addAssessment.assessmentType.$error.required">Assessment
Type is required</p>
</div>
</div>
<div class="form-group col-md-6 fieldHeight">
<label for="assessmentType" class="col-md-5 required">Assessment Type :</label>
<label class="radio-inline"><input type="radio"
name="summary" id="summary" ng-value="'summary'"
ng-model="riskAssessmentDTO.erhFlag" ng-disabled="disableAssessmentType" >Summary </label>
<label class="radio-inline"><input type="radio"
name="detail" id="detail" ng-value="'N'"
ng-model="riskAssessmentDTO.erhFlag" ng-disabled="disableAssessmentType">Detailed</label>
<p class="text-danger"
ng-show="addAssessment.includeERHFlag.$touched && addAssessment.includeERHFlag.$error.required">Assessment
Name is required</p>
</div>
</div>
main.js
$scope.assessmentType = function() {
$scope.riskAssessmentDTO.assessmentName = '';
$scope.riskAssessmentDTO.erhFlag = 'Y';
$scope.showRefineERH = false;
if ($scope.riskAssessmentDTO.scopeType === 'RA_GEO_LOCAT') {
$scope.disableAssessmentType = true;
$scope.riskAssessmentDTO.erhFlag = 'summary';
} else if ($scope.riskAssessmentDTO.scopeType === 'RA_LEGAL_ENTITY') {
$scope.disableAssessmentType = true;
$scope.riskAssessmentDTO.erhFlag = 'summary';
} else if ($scope.riskAssessmentDTO.scopeType === 'RA_BUS_UNIT') {
$scope.disableAssessmentType = false;
$scope.riskAssessmentDTO.erhFlag = 'detailed';
}
};
Use ng-disabled in Radio buttons and use a scope variable as $scope.selectedIndex to set it as false or true
<input type="radio" ng-disabled="selectedInderx==0">
and set $scope.selectedIndex in the ng-change function in Select by passing $index from html

Categories

Resources