How to calculate the total value of each section separately: Jquery - javascript

I have more than 10 section that included three inputs in each section as follows:
<div class="product_quantity">
<div class="color-quantity">
<input onkeydown="return myFunction(event);" name="custom_small" class="custom_small" type="text">
<input onkeydown="return myFunction(event);" name="custom_medium" class="custom_medium" type="text">
<input onkeydown="return myFunction(event);" name="custom_large" class="custom_large" type="text">
</div>
<div class="color-quantity">
<input onkeydown="return myFunction(event);" name="white_small" class="custom_small" type="text">
<input onkeydown="return myFunction(event);" name="white_medium" class="custom_medium" type="text">
<input onkeydown="return myFunction(event);" name="white_large" class="custom_large" type="text">
</div>
</div>
I am calculating the product quantity from each section but its giving me the whole amount of products on the basis of amount entered in every input. but i want the amount of products in section separately
I am using jQuery to do so please check the code and recommend the changes as required:
jQuery(".color-quantity input").each(function () {
if (this.value) {
quantity += (this.value) * 1;
classname = jQuery(this).attr('class');
arr.push(classname);
}
if (quantity == '') {
quantity = 0;
}
});

You can get total off each section as an array like following.
var arr = $('.color-quantity').map(function () {
var total = 0;
$('input', this).each(function () {
total += this.value * 1;
});
//do some stuff
if (total < 50) {
$('.btn-cart').removeAttr("onclick");
}
return total;
}).get();
console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-quantity">
<input type="text" value="1">
<input type="text" value="2">
<input type="text" value="3">
</div>
<div class="color-quantity">
<input type="text" value="4">
<input type="text" value="5">
<input type="text" value="6">
</div>

You might try a nested loop. first loop through the color-quantity divs, then through the inputs. like this:
jQuery(".color-quantity").each(function () {
var quantity = 0;
$(this).find('input').each(function() {
if (this.value) {
quantity += (this.value) * 1;
classname = jQuery(this).attr('class');
arr.push(classname);
}
if (quantity == '') {
quantity = 0;
}
});
// here is where you can get the total value for each div
});

Related

JavaScript function not working as desired

I'm working with HTML, JavaScript and CSS. The function objective is to create a border-radius attribute in a div element(id="surface"), and assign the value typed in inputs texts(class="chars_1") to it.
HTML
<div id="container">
<div class="input_wrapper" id="input_wrapper_tl">
<input type="text" id="input_tl" class="chars_1" value="0" onkeypress="changeSize()">
</div>
<div class="input_wrapper" id="input_wrapper_tr">
<input type="text" id="input_tr" class="chars_1" value="0" onkeypress="changeSize()">
</div>
<div class="input_wrapper" id="input_wrapper_br">
<input type="text" id="input_br" class="chars_1" value="0" onkeypress="changeSize()">
</div>
<div class="input_wrapper" id="input_wrapper_bl">
<input type="text" id="input_bl" class="chars_1" value="0" onkeypress="changeSize()">
</div>
<div id="surface">
<textarea id="code" readonly="readonly"></textarea>
<div id="options">
<input type="checkbox" checked="true" id="opt_webkit">
<label for="opt_webkit"> Webkit</label>
<input type="checkbox" checked="true" id="opt_gecko">
<label for="opt_gecko"> Gecko</label>
<input type="checkbox" checked="true" id="opt_css3">
<label for="opt_css3"> CSS3</label>
</div>
</div>
JavaScript Function
function changeSize(){
var surface = document.getElementById("surface");
var inputs = document.getElementsByClassName("chars_1");
var total = 0;
for(var x = 0; x == 3; x++){
total += Number(inputs[x].value);
}
surface.style.borderRadius = String(total)+"px";
}
First I selected both elements and assigned it to these 2 variable "surface" and "inputs". "total" being used in the "for structure" to go through every input element and select every value, and afterward convert to Number to the "total" variable.
The idea is to assign to the border-radius attribute the total variable value, which will be converted to a string so it can be recognized as a value.
Have a border
Fix the for loop for (var x = 0; x < inputs.length; x++) {
Here is an upgraded version
const changeSize = (e) => {
const tgt = e.target; // which input
if (tgt.classList.contains("chars_1")) { // ah, one of those
let total = [...document.querySelectorAll(".chars_1")].reduce(
(sum, input) => {
const val = input.value;
sum += val.trim() === "" || isNaN(val) ? 0 : +val; // only add if a number
return sum;
}, 0);
console.log(String(total) + "px")
document.getElementById("surface").style.borderRadius = String(total) + "px";
}
};
window.addEventListener("load", () => { // when page loads
document.getElementById("container").addEventListener("input", changeSize);
});
#surface {
border: 3px solid black;
}
<div id="container">
<div class="input_wrapper" id="input_wrapper_tl">
<input type="text" id="input_tl" class="chars_1" value="0">
</div>
<div class="input_wrapper" id="input_wrapper_tr">
<input type="text" id="input_tr" class="chars_1" value="0">
</div>
<div class="input_wrapper" id="input_wrapper_br">
<input type="text" id="input_br" class="chars_1" value="0">
</div>
<div class="input_wrapper " id="input_wrapper_bl ">
<input type="text" id="input_bl " class="chars_1" value="0">
</div>
<div id="surface">
<textarea id="code" readonly="readonly"></textarea>
<div id="options">
<input type="checkbox" checked="true" id="opt_webkit">
<label for="opt_webkit"> Webkit</label>
<input type="checkbox" checked="true" id="opt_gecko">
<label for="opt_gecko"> Gecko</label>
<input type="checkbox" checked="true" id="opt_css3">
<label for="opt_css3"> CSS3</label>
</div>
</div>
for(var x = 0; x == 3; x++)
that loop doesn't even execute,
change x==3 on x<3 or whatever you want to achive.
And I guess you must have border to change it's radious

add additional value to the total

I am looking for a way to add the value from (discount) and (quantity) to my total. As for discount part, the customer will need to enter the right code to receiver discount. And for quantity, when clicked at the checkbox, then change the quantity, the total will also follow. Can you guys help me out on this problem?
thanks
(sorry, my English is not good)
function addItemPrice() {
var total = 0;
var count = 0;
for (var i = 0; i < document.myform.item.length; i++) {
if (document.myform.item[i].checked) {
total = (total + document.myform.item[i].value * 1); // another way to convert string to number
count++;
}
}
return total;
}
var sh_prices = new Array();
sh_prices["standard"] = 10;
sh_prices["express"] = 20;
function getAddShipping() {
var shippingPrice = 0;
var theForm = document.forms["myform"];
var shipping = theForm.elements["shipping"]
for (var i = 0; i < shipping.length; i++) {
if (shipping[i].checked) {
shippingPrice = sh_prices[shipping[i].value];
break;
}
}
return shippingPrice;
}
function getCode() {
var theForm = document.forms["myform"];
var discode = theForm.elements["discount"]
if (discode == "UAC123") {
alert("yes");
} else {
alert("no")
}
}
function getTotal() {
var totalPrice = getAddShipping() + addItemPrice();
document.getElementById('Price').innerHTML = "the total price" + totalPrice;
}
<form name="myform">
Sickle $5 <input type="checkbox" name="item" value="5" onclick="getTotal(item)">
<input type="number" name="quantity"><br> Sickle $1 <input type="checkbox" name="item" value="1" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $50 <input type="checkbox" name="item" value="50" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $5 <input type="checkbox" name="item" value="5" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $7 <input type="checkbox" name="item" value="7" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Standard
<input type="radio" name="shipping" value="standard" onClick="getTotal(shipping)" /> Express
<input type="radio" name="shipping" value="express" onClick="getTotal(shipping)" /> <br> Discount code
<input type="text" name="discount" size=15>
<input type="button" id="code" value="check" onClick="getCode(code)">
<div id="Price">
</div>
</form>

Change prices based on checkbox click

im currently looking for help in this matter.
The problem here is that instead of doing the checkbox value + the previous value it is adding it all together like placing "10" and after other checkbox click it adds the value to it and does not count it like "1020" instead of doing 10+20
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = 0;
$("input[type=checkbox]:checked").each(
function() {
total = total + parseInt($(this).val());
});
var input = document.getElementById("valor");
input.value += input.value + total;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label><br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="10" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
Check if repeatedly click on checkbox should be handled also on uncheck score should reduced.
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = 0;
total = parseInt(document.getElementById("valor").value);
if(isNaN(total)){
total = 0;
}
if($(this).prop('checked')){
total = total + parseInt($(this).val());
} else {
total = total - parseInt($(this).val());
};
var input = document.getElementById("valor");
input.value = total;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label><br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="20" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
The code
input.value += input.value + total;
means (since input.value is a String), concatenate input.value with total after making sure total is a String. Don't use the += and be sure to use parseInt() on anything that you want to be a number.
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = 0;
$("input[type=checkbox]:checked").each(
function() {
total = total + parseInt($(this).val());
});
var input = document.getElementById("valor");
/*
* You don't need +=
* You do need to parseInt
* You need to make sure to handle empty String ""
*/
input.value = (parseInt(input.value, 10) || 0) + total;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label>
<br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="10" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
Please correct me, if I don't quite understand your problem, but shouldn't you just have to change input.value += input.value + total; to input.value = total; for the required result?
As you are using jQuery and I love to user reduce method I can advice you this solution
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = $('input[type=checkbox]:checked').toArray().reduce(function(pre, post) {
return pre + parseInt($(post).val());
}, 0);
$('#valor').val(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label><br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="20" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
If your value is always a number you can use value / 1 to convert number string into numeric type. This only if you are SURE that the number will be always a number and not a string containing number, eg. 11.jpg is not valid.
This is a performance test for your case:
https://jsperf.com/parseint-versus-divide-by-one/1
So you can rewrite the code as:
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total =
$('input[type=checkbox]:checked').toArray().reduce(function(pre, post) {
var val = $(post).val() / 1;
return pre + (val ? val : 0);
}, 0);
$('#valor').val(total);
});
});

Sum dynamic values from input text and radio

I'm trying to sum the value of an input text changing dynamically with a radio that also changes dynamically. I'm doing something right but also something wrong because it doesn't sum when I want. The sum should show everytime the input text changes and not randomly disappear then you click a radio, just sum them.
the fiddle http://jsfiddle.net/7tFhx/
and the code
<form id="myForm" accept-charset="UTF-8">
<button type="button" class="btn-tt btn-primary btn-lg" disabled>1. Elige el color</button></br>
<label>
<input class="calc" id="fb1" type="radio" name="fb" value="10">
<img src="img/01.jpg"/>
</label>
<label>
<input class="calc" id="fb2" type="radio" name="fb" value="15">
<img src="img/02.jpg"/>
</label>
</br>
</br>
<button type="button" class="btn-tt btn-primary btn-lg" disabled>2. Elige las medidas</button></br>
<div class="row">
<div class="col-xs-2">
ancho (cm.)
<input id="ancho" type="text" class="form-control" placeholder="100">
</div>
<div class="col-xs-2">
alto (cm.)
<input id="alto" type="text" class="form-control" placeholder="100">
</div>
<div class="col-xs-2">
cantidad
<input id="cantidad" type="text" class="form-control" placeholder="1">
</div>
</div>
</br>
<button type="button" class="btn-tt btn-primary btn-lg" disabled>3. Posición mecanismo</button></br>
<label>
<input class="calc" id="fb3" type="radio" name="fb1" value="20">
<img src="img/01.jpg"/>
</label>
<label>
<input class="calc" id="fb4" type="radio" name="fb1" value="35">
<img src="img/02.jpg"/>
</label>
<div>
Total: <span id="price">0</span>€
</div>
</form>
js:
$(function(){
var mecanismoMedida = ['100','200'];
var mecanismoPrecio = ['50','80'];
$('#ancho').on('input',function(){
var j = 1, i = 0;
value = parseInt(($("#ancho").val() / 8) + 1);
for(i = 0; i < mecanismoMedida.length; i++){
if($("#ancho").val() >= mecanismoMedida[i] && $("#ancho").val() <
mecanismoMedida[j]){
value += mecanismoPrecio[i];
break;
} else {
j++;
}
}
$("#price").text(this.value + value);
});
$('#myForm input[type="radio"]').on('change', function () {
var sum = 0;
$("#myForm").find("input[type='radio']:checked").each(function () {
sum += parseInt(this.value);
});
$("#price").text(sum);
});
});
If it's a simple sum you're after, you can simply run an update code on the keyup and change events of all input elements:
$("input").change(function(){update();}).keyup(function(){update();});
To update them, first you need to check and see which one of the two radio buttons are checked and get its value:
function update(){
var p = 0;
for(var i = 0; i < $(".calc").val(); i++)
{
if($($(".calc")[i]).prop("checked") == true)
{
p += parseInt($($(".calc")[i]).val());
}
}
After that, simply parse the values of the textboxes to integers and add them to the value of the radio button. I created a custom function to do this, because if the boxes are empty, parsing them returns NaN:
p = parseInt(p);
p += parseInt(val2($("#ancho")));
p += parseInt(val2($("#alto")));
p += parseInt(val2($("#cantidad")));
p = parseInt(p);
$("#price").html(p);
}
function val2(elm){
if(isNaN(parseInt($(elm).val())))
return 0;
else
return parseInt($(elm).val());
}
JSFiddle

Javascript multiple update the same field

FIDDLE: http://jsfiddle.net/hReB3/6/
Javascript code:
$('#qty').keyup(function(){
if($(this).val() != '' && isNumber($(this).val()) && $(this).val() > 0)
{
var price = $('#real_price').val() * 1;
var qty = $(this).val() * 1;
var total = price * qty;
$('#price').html(total);
}
else
{
$('#price').html('500');
}
});
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
If I'm updating the price for the first field, it works fine, but for the second doesnt.
I'm new into javascript :).
JSFiddle
Using classes on your fields instead of IDs (IDs must be unique) and enclosing them within a parent DIV would allow you to use this code and gives you scope to add as many sections to your page as you need.
HTML
<div>
Price $<span class="price">500</span>
<input type="hidden" class="real_price" value="500" />
<input type="text" class="qty" value="1" />
</div>
<div>
Price $<span class="price">500</span>
<input type="hidden" class="real_price" value="500" />
<input type="text" class="qty" value="1" />
</div>
JS
$('.qty').keyup(function () {
var $me = $(this),
$parent = $me.parent('div'),
total = 500;
if (isNumber($me.val()) && $me.val() > 0)
{
var price = $parent.find('.real_price').val() * 1,
qty = $me.val() * 1;
total = price * qty;
}
$parent.find('.price').html(total);
});
You could also replace your hidden fields with data-price attributes as shown here JSFiddle
Can you try this, You can't able to use id value in more elements, instead that you can use classname etc, I have updated your fiddle code,
HTML:
Price $<span id="price_qty_1">500</span>
<input type="hidden" id="real_price_qty_1" value="500" />
<input type="text" id="qty_1" class="qty" value="1"/><br />
Price $<span id="price_qty_2">500</span>
<input type="hidden" id="real_price_qty_2" value="500" />
<input type="text" id="qty_2" class="qty" value="1"/>
Jquery:
$('.qty').keyup(function(){
if($(this).val() != '' && isNumber($(this).val()) && $(this).val() > 0)
{
var idAt = $(this).attr('id');
var price = $('#real_price_'+idAt).val() * 1;
var qty = $(this).val() * 1;
var total = price * qty;
$('#price_'+idAt).html(total);
}
else
{
$('#price_'+idAt).html('500');
}
});
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Demo : http://jsfiddle.net/hReB3/10/
Try this
<input type="text" id="qty1" value="1"/><br />
<input type="text" id="qty2" value="1"/>
$('#qty1,#qty2').keyup(function(){})
And in the price evaluation time replace this with
$('#price').html(total);
with
($(this).attr('id')=="qty1") ? $('#price1').html(total) : $('#price2').html(total);

Categories