calculations on multiple selects dropdown - javascript

I am trying calculate the amount on change of select dropdown. I need each row calculation front of that row i.e. subtotal and all subtotal will be at bottom at "Total Amount"
I am getting the calculations for first row, but there is issues somewhere, i cannot findout properly. Please help me.
My code is
jQuery(document).ready(function() {
var bookIndex = 1;
jQuery('#orderform')
// Add button click handler
.on('click', '.addButton', function() {
bookIndex++;
var $template = jQuery('#bookTemplate'),
$clone = $template
.clone()
.removeClass('hide')
.addClass('form-group')
.removeAttr('id')
.removeAttr('style')
.attr('id', "row"+bookIndex)
.attr('data-index', bookIndex)
.insertBefore($template);
jQuery("#row"+bookIndex+' .addprice span').addClass('item_price');
jQuery("#row"+bookIndex+' .addprice input').addClass('itemprice');
jQuery("#row"+bookIndex+' > div ').removeClass('addprice');
// Add new fields
// Note that we also pass the validator rules for new field as the third parameter
var totalamount = 0;
var price =0;
jQuery('.dynamic-fields > .form-group').each(function () {
price = jQuery("span.item_price").html();
totalamount += parseFloat( price );
});
jQuery("#totalamount > span").html(totalamount);
jQuery("#totalamount").attr('data-amount', totalamount);
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = jQuery(this).parents('.form-group'),
index = $row.attr('data-book-index');
// Remove fields
// Remove element containing the fields
$row.remove();
var totalamount = 0;
var price =0;
jQuery('.dynamic-fields > .form-group').each(function () {
price = jQuery("span.item_price").html();
totalamount += parseFloat( price );
});
jQuery("#totalamount > span").html(totalamount);
jQuery("#totalamount").attr('data-amount', totalamount);
});
});
jQuery(document).ready(function(){
var totalamount = 0;
var price =0;
jQuery('.dynamic-fields > .form-group').each(function () {
price = jQuery("span.item_price").html();
totalamount += parseFloat( price );
});
jQuery("#totalamount > span").html(totalamount);
jQuery("#totalamount").attr('data-amount', totalamount);
})
jQuery(".dynamic-fields").each(function() {
var tpy = parseInt(jQuery(".service_type option:selected").val());
var clths = parseInt( jQuery(".cloths option:selected").val() );
var quantity = parseInt( jQuery(".quantity option:selected").val() );
var total;
total= tpy + clths * quantity;
jQuery("span.item_price").html(total);
jQuery("input.itemprice").attr('value', total);
});
jQuery(document).on("change", '.dynamic-fields > div.form-group select', function() {
var total = 0;
var id = jQuery(this).parent().parent().attr('id');
var index = jQuery(this).parent().parent().attr('data-index');
id = '#'+id+' '; //alert(id); //alert(index);
//jQuery('.form-group').each(function () {
var tpy = jQuery(id+'.service_type option:selected').val();
var clths = jQuery(id+'.cloths option:selected').val();
var quantity = jQuery(id+'.quantity option:selected').val();
total= ( parseInt(tpy) + parseInt(clths) ) * parseInt(quantity);
jQuery(id+".item_price").html(total);
jQuery(id+".itemprice").attr('value', total);
//});
var totalamount = 0;
var price =0;
jQuery('.accept-checkbox.dynamic-fields > div.form-group').each(function () {
price = jQuery("span.item_price").html();
totalamount += parseFloat( price );
});
jQuery("#totalamount > span").html(totalamount);
jQuery("#totalamount").attr('data-amount', totalamount);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form name="neworder" action="<?php the_permalink(); ?>" method="post" id="orderform">
<div class="accept-checkbox dynamic-fields">
<div class="form-group" id="row1" data-index="1">
<div class="col-sm-3">
<select class="service_type" name="service_type[]">
<option value="20">Iron</option>
<option value="30">Wash</option>
<option value="40">Wash & Iron</option>
<option value="50">Dryclean</option>
</select>
</div>
<div class="col-sm-3">
<select class="cloths" name="cloths[]">
<option value="10">Shirt</option>
<option value="20">Tshirt</option>
<option value="30">Kurta</option>
<option value="40">Jeans</option>
<option value="50">Trouser</option>
<option value="60">Trouser</option>
</select>
</div>
<div class="col-sm-3">
<select class="quantity" name="quantity[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="3">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div class="col-sm-2">
<span class="item_price">30</span>
<input type="hidden" class="itemprice" value="00"/>
</div>
<div class="col-sm-1">
<button class="btn btn-default addButton" type="button"><i class="fa fa-plus">+</i></button>
</div>
</div>
<!-- The template for adding new field -->
<div id="bookTemplate" class=" hide" style="display: none;">
<div class="col-sm-3">
<select class="service_type" name="service_type[]">
<option value="20">Iron</option>
<option value="30">Wash</option>
<option value="40">Wash & Iron</option>
<option value="50">Dryclean</option>
</select>
</div>
<div class="col-sm-3">
<select class="cloths" name="cloths[]">
<option value="10">Shirt</option>
<option value="20">Tshirt</option>
<option value="30">Kurta</option>
<option value="40">Jeans</option>
<option value="50">Trouser</option>
<option value="60">Trouser</option>
</select>
</div>
<div class="col-sm-3">
<select class="quantity" name="quantity[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="3">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div class="col-sm-2 addprice">
<span >30</span>
<input type="hidden" value="00"/>
</div>
<div class="col-xs-1">
<button class="btn btn-default removeButton" type="button"><i class="fa fa-minus"> - </i></button>
</div>
</div>
</div>
<div class="row">
<div class="col-md-5 pull-right">
<span><strong>Total Amount : </strong></span><span id="totalamount"> <span>00.00</span>/- </span>
</div>
</div>
</form>

The added elements do not have an event handler.
To write one event handler for current and future elements, replace this:
jQuery('.dynamic-fields > div.form-group select').on("change", function () {
With:
jQuery(document).on("change", '.dynamic-fields > div.form-group select', function() {
Note that you still have many issues with your code. You should better keep your quantities, prices, etc.. (also) in variables, and not re-read them every time from html attributes.
For instance these lines are now wrong:
jQuery(".item_price").html(total);
jQuery("input.itemprice").attr('value', total);
You intended this:
jQuery(id+".item_price").html(total);
jQuery(id+".itemprice").attr('value', total);
... and there are more issues like that, but if I were you, I would refactor this code to rely less on the html attributes for calculating the total.

change the line
jQuery('.dynamic-fields > div.form-group select').on("change", function() { ...
to
jQuery(document).on("change", '.dynamic-fields > div.form-group select', function() { ...
because the EventListener change is bind once to the elements that are at the time in DOM the code is executed with selector .dynamic-fields > div.form-group select.
Now the EventListener is set to the document und the function is executed when event.target is .dynamic-fields > div.form-group select.

Related

Update Array with dynamically generated values

I'm very new to JavaScript, so I'm having a hard time with this relatively simple problem:
I wrote a function that dynamically adds or removes dropdown fields to the DOM if the user clicks the add or remove button. So far so good, everything is working fine until here.
Now I want to collect the data in an Array to send it to the api.
With the following code I can collect it, but I have a hard time to figure out how I can remove specific values from the array.
<div class="container mt-2" id="stores">
<div class="row">
<div class="col">
<h2>Marktet</h2>
<div class="col-form-label storesHint">Select at least one market</div>
</div>
</div>
<div id="form">
<div>
<div id="addAnotherMarket">
<div class="marketRow">
<select class="form-control" id="market" name="market">
<option value="1"> market1</option>
<option value="2"> market2</option>
<option value="3"> market3</option>
<option value="4"> market4</option>
<option value="5"> market5</option>
</select>
<input class="deleteButton" type="button" id="remove" value="" style="display: none; font-family: FontAwesome, 'Helvetica Neue', Helvetica, Arial, sans-serif;">
</div>
</div>
</div>
</div>
<div>
<div class="addBtnContainer">
<div class="centerBtn">
<a class=" button btn_gray buttonWithIcon" id="add">
<i class=" fa fa-plus icn" id="btnIcon" style="font-size: 16px;" aria-hidden="true"></i>
<span class="btnText spn" style="top:0px !important">Add another market</span>
</a>
</div>
</div>
</div>
</div>
$(document).ready(function () {
let index = 0;
let store = {};
let stores = [];
var oldValue = [];
window.Stores = stores;
//set initial value for the first dropdown element
store = { "store_id": parseInt($('#market').val(), 10) };
stores.push(store);
oldValue[index] = store;
//update value if user changes first element
$('#market').on('change', function () {
store = { "store_id": parseInt($(this).val(), 10) };
var eleIndex = stores.indexOf(oldValue[index]);
if (eleIndex !== -1) {
stores.splice(eleIndex, 1, store);
oldValue[index] = store;
}
});
//add a new dropwdown element
$("#add").click(function () {
index++;
$(this).parent().parent().before($("#form").clone().attr("id", "form" + index));
$("#form" + index + " :input").each(function () {
$(this).attr("name", $(this).attr("name") + index);
$(this).attr("id", $(this).attr("id") + index);
});
//set initial value of the new dropdown element
store = { "store_id": parseInt($('#market' + index).val(), 10) };
stores.push(store);
oldValue[index] = store;
//set new value if user changes value
$('#market' + index).on('change', function () {
store = { "store_id": parseInt($(this).val(), 10) };
var eleIndex = stores.indexOf(oldValue[index]);
if (eleIndex !== -1) {
stores.splice(eleIndex, 1, store);
oldValue[index] = store;
}
});
//add remove button
$("#remove" + index).css("display", "inline-flex");
$(".marketRow").css({
'display': 'flex',
'align-items': 'center',
'margin-top': '5px'
});
//if user clicks remove button delete value from array
$("#remove" + index).click(function () {
var eleIndex = stores.indexOf({ "store_id": parseInt($('#market' + index).val(), 10) });
if (index !== -1) {
stores.splice(eleIndex, 1);
oldValue.splice(eleIndex);
}
$(this).closest("div").remove();
});
});
});
The following code also outputs -1 always, so I think indexOf makes no sense.
var eleIndex = stores.indexOf({"store_id": parseInt($('#market' + index).val(), 10)});
EDIT: I updated the post with the HTML part as requested. In short: When clicking on button(#add) div(#form) will be cloned, remove button will be added, and id's will be updated with index.
Values of all these selects will be stored and updated in the stores array. I just can't delete them.
I have also provided a working jsfiddel https://jsfiddle.net/proach1995/h1gtmyen/
With plain js you can add class to the dropdown you wish to collect from. in the code below it will build the array only if value was selected.
if you use jQuery you can replace document.querySelectorAll('.store'); with $('.store');
function saveArray() {
const selected = document.querySelectorAll('.store');
const stores = [];
selected.forEach(prop => {
if (!!prop.value) {
stores.push({store_id: parseInt(prop.value, 10)})
}
});
console.log(stores);
}
<select class="store">
<option disabled selected value>select value</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="store">
<option disabled selected value>select value</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<select class="store">
<option disabled selected value>select value</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<button onclick="saveArray()">save array</button>

how to Remove last selected value

I am trying to add values with the help of jquery But last value + in code again and again
The last value should be cleared when select new value from dropdown
var lastSelected;
$(document).ready(function() {
$("#selectchild1").on('change', function() {
$("div").remove("select");
var childvalue = this.value;
alert(childvalue);
var count = $(this).val();
newContent = "";
name = $(this).attr("name");
var j = 1;
var k = 0;
for (var i = 0; i < count; i++) {
newContent += $("#addedchild1").append("<div class='col-md-2 col-lg-2 text-center'><div class='form-group'>Child-" + j + " Age <select name='RoomTypes[" + k + "][]'><option value='0'>Age</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option><option value='6'>6</option><option value='7'>7</option><option value='8'>8</option><option value='9'>9</option><option value='10'>10</option><option value='11'>11</option><option value='12'>12</option><select></div></div>");
j++;
}
content.html(newContent);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectchild1" class="form-control">
<option value="0">00</option>
<option value="1">01</option>
<option value="2">02</option>
<option value="3">03</option>
<option value="4">04</option>
<option value="5">05</option>
<option value="6">06</option>
</select>
<div class="col-xs-3 col-sm-3 col-md-8 text-right">
<div id="addedchild1"></div>
</div>
I think you mean this
newContent += $("#addedchild1"). is not doing what you think it is
There is no content declared
You do not need to remove anything if you use .html() it replaces the HTML
I think you do not want addedChild1 but all the added children in the div I gave ID="wrapper" - if you want to nest in a addedChild, just change #wrapper to #addedChild1
$(function() {
$("#selectchild1").on('change', function() {
var count = +$(this).val();
name = $(this).attr("name");
const newContent = Array.from(Array(count+1).keys()) // cleate an array from 0 to count+1
.slice(1) // get rid of the `0` to use ${i} from `1`
.map(i => (`<div class='col-md-2 col-lg-2 text-center'><div class='form-group'>Child-${i} Age <select name='age'><option value='0'>Age</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option><option value='6'>6</option><option value='7'>7</option><option value='8'>8</option><option value='9'>9</option><option value='10'>10</option><option value='11'>11</option><option value='12'>12</option><select></div></div>`))
$("#wrapper").html(newContent.join("")); // add the array to the wrapper after joining it
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectchild1" class="form-control">
<option value="0">00</option>
<option value="1">01</option>
<option value="2">02</option>
<option value="3">03</option>
<option value="4">04</option>
<option value="5">05</option>
<option value="6">06</option>
</select>
<div id="wrapper" class="col-xs-3 col-sm-3 col-md-8 text-right">
</div>
First of all there is an error in your code. There is no variable named content.
Uncaught ReferenceError: content is not defined
You should add the following line to your code.
$('#addedchild1 div').remove();
I hope I understood your problem and I hope I was able to help you.
Check the example here: https://codepen.io/yasgo/pen/ExyqWvy

Having trouble with Javascript ordering form not calculating

So I'm getting a null error with my order form when I'm trying to calculate the total using javascript. I believe I have everything done. I get an error on line 13 below that starts with .innerHTML
<script type="text/javascript">
function doTotals() {
var strains = ['guptakush_', 'headbandguptakush_', 'purplejuicyfruitguptakush_', 'hibiscussunrise_', 'criticalkushguptakush_', 'columbiagoldguptakush_', 'grapeapeguptakush_', 'krishnakush_', 'durbinpoisonguptakush_', 'purpleeurkleguptakush_', 'columbiagoldafgani_', 'kandykushguptakush_', 'hibiscussunriseafgani_', 'afgani_', 'grapeapeafgani_', 'krishnaafgani_', 'hashplantafgani_', 'durbinpoisonafgani_'];
var priceStr = 'price';
var quantityStr = 'quantity';
var subtotalStr = 'subtotal';
var total = 0.00;
for (var i = 0; i < strains.length; i++) {
var price = document.getElementById(strains[i] + priceStr).value;
var quantity = document.getElementById(strains[i] + quantityStr).value;
document.getElementById(strains[i] + subtotalStr)
.innerHTML = parseInt(price) * parseInt(quantity);
total += price * quantity;
}
document.getElementById("finaltotal").innerHTML = total;
}
function setup() {
var lastCol = document.getElementById("subtotal_header");
var theForm = document.getElementById("orderform");
var amounts = document.getElementsByTagName("select");
for(var i = 0; i < amounts.length; i++){
amounts[i].onchange = doTotals;
}
}
window.onload = setup;
</script>
Here is the HTML that is associated just one example they are all the same with unique id and names.
<div class="form-group mb-3">
<label class="form-control-label" for="guptakush_quantity">Gupta Kush</label>
<input type="hidden" id="guptakush_price" value="1.00">
<select class="form-control-inline form-control-sm" id="guptakush_quantity" name="guptakush_quantity" size="1">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<input type="hidden" id="guptakush_subtotal">
</div>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">$</div>
</div>
<input type="text" class="form-control-inline col-sm-1" id="finaltotal" name="finaltotal" placeholder="$0.00" readonly>
</div>
Full Example:
https://jsfiddle.net/dg260zxf/
Also if I could just make this work without the subtotal since I don't think it's necessary that would be awesome.
the problem is the array contains many Divs than not in HTML,
the first item 'guptakush_' only exist in html
so if you check if div exists before settings value it will resolve the problem
+
the finaltotal is input not html so put new value with .value not .inerHTML
Working demo:
function doTotals() {
var strains = ['guptakush_', 'headbandguptakush_', 'purplejuicyfruitguptakush_', 'hibiscussunrise_', 'criticalkushguptakush_', 'columbiagoldguptakush_', 'grapeapeguptakush_', 'krishnakush_', 'durbinpoisonguptakush_', 'purpleeurkleguptakush_', 'columbiagoldafgani_', 'kandykushguptakush_', 'hibiscussunriseafgani_', 'afgani_', 'grapeapeafgani_', 'krishnaafgani_', 'hashplantafgani_', 'durbinpoisonafgani_'];
var priceStr = 'price';
var quantityStr = 'quantity';
var subtotalStr = 'subtotal';
var total = 0.00;
for (var i = 0; i < strains.length; i++) {
var priceInput = document.getElementById(strains[i] + priceStr);
var quantityInput = document.getElementById(strains[i] + quantityStr);
var subTotalDiv = document.getElementById(strains[i] + subtotalStr);
if(subTotalDiv) {
var price = priceInput.value;
var quantity = quantityInput.value;
subTotalDiv
.innerHTML = parseInt(price) * parseInt(quantity);
total += price * quantity;
}
}
document.getElementById("finaltotal").value = total;
}
function setup() {
var lastCol = document.getElementById("subtotal_header");
var theForm = document.getElementById("orderform");
var amounts = document.getElementsByTagName("select");
for(var i = 0; i < amounts.length; i++){
amounts[i].onchange = doTotals;
}
}
window.onload = setup;
<div class="form-group mb-3">
<label class="form-control-label" for="guptakush_quantity">Gupta Kush</label>
<input type="hidden" id="guptakush_price" value="1.00">
<select class="form-control-inline form-control-sm" id="guptakush_quantity" name="guptakush_quantity" size="1">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<input type="hidden" id="guptakush_subtotal">
</div>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">$</div>
</div>
<input type="text" class="form-control-inline col-sm-1" id="finaltotal" name="finaltotal" placeholder="$0.00" readonly>
</div>
Plenty of issues:
You hadn't defined subtotalStr, so that was null
You weren't executing your setup function because you didn't include parentheses
Your <strong> element doesn't seem to be populatable when selecting it by ID (not sure what was up w/that, but changing it to a div worked).
Check this: https://jsfiddle.net/mj1z9bvq/
In my version, I fixed the first two problems. And then for the first <strong> element, I replaced it with a <div> so you could see the output. You'll have to go through and do something similar for the others.

Problem while adding many options to multiple select js

I'm pretty new to JS, and I want to add many options to multiple select. But the problem is that when I'm trying to show them only the last record is triggering the function (showing). But when I'm doing console.log it is showing every thing perfectly.
This is my HTML:
<form class="cart" method="post" action="{{ route('cart.add') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="product_size" class="grey">Model</label>
<span class="red">*</span>
<select class="form-control" id="productModel" name="product" onchange=" addRelatedproducts();">
<option value="">Wybierz model produktu...</option>
#foreach($productModels as $productModel)
<option value="{{$productModel->id}}">{{$productModel->modelName}} - {{$productModel->modelPrice}} #if($productModel->modelPriceCurrency === 1) PLN #else EUR #endif</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="exampleSelect1">Ilość:</label>
<select class="form-control" id="exampleSelect1" name="quantity">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<div>
<div class="form-group" id="relatedProductsDiv" style="display: none;">
<label for="exampleSelect1">Produkty powiązane:</label>
<select id="select" multiple="multiple" class="relatedProducts" name="relatedProduct">
</select>
</div>
</div>
This is my JS:
function addRelatedproducts(){
var model = [
<?php foreach($productModels as $productModel):?>
<?=$productModel?>,
<?endforeach;?>
];
var relatedProducts = [
<?php foreach($relatedProductArray as $relatedProduct): ?>
<?=$relatedProduct ?>,
<?endforeach; ?>
];
var e = document.getElementById("productModel");
var selectedModelId = e.options[e.selectedIndex].value;
var select = document.getElementById("select");
for (var i = 0; i < relatedProducts.length + 1; i++) {
select.remove(relatedProducts[i].relatedProductName);
if(parseInt(relatedProducts[i].model_id) === parseInt(selectedModelId)){
console.log(relatedProducts[i])
console.log(selectedModelId)
document.getElementById("relatedProductsDiv").style.display = "";
var option = document.createElement("option");
option.value = relatedProducts[i].id;
option.text = relatedProducts[i].relatedProductName;
select.add(option);
}
else{
document.getElementById("relatedProductsDiv").style.display = "none";
}
}
}
I don't really know why it isn't working. Can anybody help me with this problem?
select.remove(relatedProducts[i].relatedProductName);
select.remove expects an option index as an argument. And I suppose when it receives a product name string (probably not a number) apparently it evaluates it as NaN and just removes the very first option in the select on every step. So it comes up with an empty select in the end.
Maybe the better approach would be to clear all the select options right before iterating relatedProducts and then to populate only with the needed ones?
while(select.options.length) {
select.remove(0);
}
for (var i = 0; i < relatedProducts.length + 1; i++) {
if(parseInt(relatedProducts[i].model_id) === parseInt(selectedModelId)){
console.log(relatedProducts[i])
// ....

How to associate two inputs in JavaScript?

I have this code:
$(document).ready(function(){
$('.container select').each(function(){
$(this).on('change', function(){
var selectedVal = $(this).val();
//console.log(selectedVal);
});
});
$('input').on('change', function () {
var sum = 0;
$('input').each(function() {
sum += Number($(this).val());
});
$('.total span').html(sum);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<div class='full'>
<input type='number' value=''>
<select name='select1'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='full'>
<input type='number' value=''>
<select name='select2'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='full'>
<input type='number' value=''>
<select name='select3'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='total'>
Total nr: <span>5(2 A1, 3 A2)</span>
</div>
</div>
Is it possible that on change of the select and the input of type number to modify the total number like in the code above using JavaScript/jQuery?
Can anyone help me with this please.
On every change on the inputs or select fields I need to calculate total number of A1 and total number of A2. Hope this make sense. And display them beside the total number.
JSFiddle
We can't give you the full code but I tried to provide some logic for what you want.I think you want some thing like this:
//create a json to collect the sum of numbers
var number = {
a1: 0,
a2: 0,
a1_count:0,
a2_count:0
};
//check in select change
$(".select").change(function() {
//flush previous calculation before using again
number.a1=0,number.a2=0,number.a1_count=0,number.a2_count=0;
//check all the select value and get the corresponding input value
$(".select").each(function() {
var valueType = $(this).val();
if (valueType == "a1") {
number[valueType+"_count"]=number[valueType+"_count"]+1;
number[valueType] = number[valueType] + parseInt($(this).prev().val()||0);
} else if (valueType == "a2") {
number[valueType+"_count"]=number[valueType+"_count"]+1;
number[valueType] = number[valueType] + parseInt($(this).prev().val()||0);
}
});
$("#total").html('Total:'+(number.a1+number.a2)+',A1:'+number.a1+'('+number.a1_count+'),A2:'+number.a1+'('+number.a2_count+')');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<div class='full'>
<input type='number' value=''>
<select name='select1' class='select'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='full'>
<input type='number' value=''>
<select name='select2' class='select'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='full'>
<input type='number' value=''>
<select name='select3' class='select'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='total' id="total">
</div>
</div>
This will work for any arbitrary list in the select.
function change() {
var res = {}, fulls = $('.container .full');
fulls.each(function(index){
var selected = $(this).find('select > option:selected').text();
if (! res[selected]) res[selected] = 0;
res[selected] += 1*$(this).find('input[type="number"]').val();
});
var detail = "", total = 0;
for(prop in res) {
if (res.hasOwnProperty(prop)) {
try {
var val = 1*res[prop];
detail += ", "+val+" "+prop;
total += val;
}catch(e){}
}
}
$('.total > span').text(""+total+" ("+detail.substr(2)+")");
}
$().add('.container .full input[type="number"]')
.add('.container .full select[name^="select"]')
.on('change', change);

Categories