The problem is that a selection of elements sumirovalis each other .. The value of the element specified in the "data-price". My code is not valid and is not handled properly, it is desirable to change the amount at any depression.
Thank you for any assistance conditional
html
<input name="tarifs" id="tarifs2" type="radio" data-price="590" value="Abs">
<input name="tarifs" id="tarifs1" type="radio" data-price="540" value="Abs"><br/>
<input name="tv[]" id="tv3" type="checkbox" data-price="150" value="Abs">
<input name="tv[]" id="tv2" type="checkbox" data-price="100" value="Abs"><br/>
<input name="tv2[]" id="tv4" type="checkbox" data-price="250" value="Abs">
<input name="tv2[]" id="tv5" type="checkbox" data-price="350" value="Abs"><br/>
Sum: <span id="checkout-sum"></span></div>
JS
$("input[name=tarifs]").keyup(function() {
var sum1 = $("input[name=tarifs]").data("price");
var sum2 = $("input[name=tv[]]").data("price");
var sum3 = $("input[name=tv2[]]").data("price");
var total = sum1 + sum2 + sum3;
$("#checkout-sum").val(total);
});
jsfiddle demo
Will use change event and only look for checked inputs. This will work when any of the radios or checkboxes shown changes
$inputs=$('#tarifs1,#tarifs2,#tv2,,#tv3,#tv4,#tv5').change(function(){
var total=0;
$inputs.filter(':checked').each(function(){
total+= $(this).data('price');
});
$("#checkout-sum").text(total);
})
DEMO
Try using this:-
$("input").change(function() {
var sum1 = $("input[name='tarifs']:checked").data("price"),
sum2 = 0,
sum3= 0;
$.each($("input[name='tv[]']:checked"), function(index,item) {
sum2 += $(item).data('price');
});
$.each($("input[name='tv2[]']:checked"), function(index,item) {
sum3 += $(item).data('price');
});
var total = +sum1 + sum2 + sum3;
$("#checkout-sum").html(total);
});
Try this :
Your missing quotes in jQuery selector: $("input[name='tv[]']
$("input[name=tarifs],[name='tv[]'],[name='tv2[]']").change(function() {
var sum1 = $("input[name=tarifs]:checked").data("price");
var sum2 = $("input[name='tv[]']:checked").data("price");
var sum3 = $("input[name='tv2[]']:checked").data("price");
var total = sum1 + sum2 + sum3;
$("#checkout-sum").html(total);
});
Demo
another way:
$input = $("input[name=tarifs],[name='tv[]'],[name='tv2[]']");
$input.change(function() {
var sum = 0;
$input.filter(':checked').each(function(){
sum = sum + $(this).data("price");
});
$("#checkout-sum").html(sum);
});
Demo
Related
I have 48 inputs, and for each input I need to get its value and add it to the total sum. Currently I am only getting the values of two inputs and adding them but how would it be better to make this a "foreach function"
$(document).ready(function() {
$('.margin .custom-input:nth-child(1)').change(function() {
updateTotal();
});
$('.margin .custom-input:nth-child(2)').change(function() {
updateTotal();
});
var updateTotal = function () {
var input1 = parseInt($('.margin .custom-input:nth-child(1)').val());
var input2 = parseInt($('.margin .custom-input:nth-child(2)').val());
var total = input1 + input2;
$(".marginAttachment").text("Durchschn. Attachmentniveau = " + total + "mm");
};
});
<div class="margin">
<input class="custom-input" type="text" value="0">
</div>
You have to use the jQuery each function. your final code will be like this
$(document).ready(function() {
$('.margin .custom-input').change(function() {
updateTotal();
});
var updateTotal = function () {
var total = 0;
$('.margin .custom-input').each(function() {
total += parseInt($(this).val());
});
$(".marginAttachment").text("Durchschn. Attachmentniveau = " + total + "mm");
};
});
Or, you just directly get the value of active input so that no need to implement for loop. like this
$(document).ready(function() {
var total = 0
$('.margin .custom-input').change(function() {
total += $(this).val()
$(".marginAttachment").text("Durchschn. Attachmentniveau = " + total + "mm");
});
});
jQuery does have foreach support, in form of the .each() function:
var sum = 0;
$('.margin .custom-input').each(function() {
sum += parseInt($(this).val());
});
I am very new at JavaScript so a step by step answer would be much appreciated. Right now my code is set up so when you click the submit button it displays the total but instead I would like the total to be updated automatically by just checking the checkboxes and to not have a submit button at all.
function calcTotal()
{
var itemTotal = 0;
var items = document.getElementsByTagName("input");
for (var i = 0; i < 5; i++) {
if (items[i].checked){
itemTotal += parseInt(items[i].value);
}
}
document.getElementById("total").innerHTML = "Your order total is $" + itemTotal +".00";
}
var submitButton = document.getElementById("sButton");
submitButton.addEventListener("click", calcTotal);
Actually you need to bind Checkbox's event change, instead of Form submit button click. That whenever you change checkbox value by checking or unchecking it, It call the function calcTotal() to update the value.
Here is updated Javascript code:
function calcTotal()
{
var itemTotal = 0;
var items = document.getElementsByTagName("input");
for (var i = 0; i < 5; i++) {
if (items[i].checked){
itemTotal += parseInt(items[i].value);
}
}
document.getElementById("total").innerHTML = "Your order total is $" + itemTotal +".00";
}
var checkBoxItems = document.getElementsByTagName("input");
checkBoxItems.addEventListener("change", calcTotal);
Hope it will help you.
Just add a change event to every checkbox. When you toggle the checked state, recalculate the total by grabbing the :checked checkboxes.
Array.from(document.querySelectorAll('input[type="checkbox"]')).forEach(chk => {
chk.addEventListener('change', recalculateTotal);
});
function recalculateTotal() {
let total = Array.from(document.querySelectorAll(':checked')).reduce((sum, chk) => {
return sum + parseInt(chk.value, 10);
}, 0);
document.getElementById('total').innerHTML = '$' + total.toFixed(2);
}
label { display: inline-block; margin-right: 1em; }
div { margin-top: 1em; }
<label>$1 <input type="checkbox" value="1" /></label>
<label>$10 <input type="checkbox" value="10" /></label>
<label>$100 <input type="checkbox" value="100" /></label>
<div>Your order total is: <span id="total">$0.00</span></div>
The key is listening to the input event on the input elements instead of the click event on the button element.
Additional notes, when possible:
Use single quotes in JS, double quotes in HTML
Use let or const instead of var
Don't reinvent .reduce when you need to reduce an array of values into a single value (e.g. compute a sum).
Use template strings (e.g. `y: ${y}`) instead of concatenating strings (e.g. "y: " + y).
let inputs = [...document.querySelectorAll("input")];
let calcTotal = () => {
let sum = inputs.reduce((sum, input) => sum + (input.checked ? parseInt(input.value) : 0), 0);
document.querySelector("#total").textContent = `Your order total is $${sum}.00`;
};
inputs.forEach(input => input.addEventListener('input', calcTotal));
<label><input type="checkbox" value=30>$30 hamburger</label>
<label><input type="checkbox" value=45>$45 french fries</label>
<label><input type="checkbox" value=1>$1 cola</label>
<label><input type="checkbox" value=60>$60 parking</label>
<label><input type="checkbox" value=20>$20 cookie</label>
<label><input type="checkbox" value=290>$290 large cookie</label>
<div id="total"></div>
I'm beginer in js, please help me.
I have two functions. First function sum all checked input ticket and view sum price, secondary function check discount code and takes into account the new price.
The problem is when I add a discount code and then will choose a ticket. Then it does not calculate the value.
https://jsfiddle.net/wznvfkm3/
$('.participantEventTicket').on('change', function() {
var totalPrice = 0.00;
$('.participantEventTicket:checked').each(function() {
totalPrice += parseFloat($(this).data('price'), 10);
});
$('.participantEventTicketSum').html(totalPrice.toFixed(2));
$('.participantEventTicketDiscountValueTotal').html(totalPrice);
});
$('.participantEventTicketDiscount').on('change', function() {
var code = ($(this).val());
var valueTotal = document.getElementById('participantEventTicketSum').innerHTML;
var value = 0;
var liste = [];
liste[0] = ['ABB'], -5]; liste[1] = ['BBC'], -10];
for (var i = 0, len = liste.length; i < len; i++) {
if (liste[i][0] === code) {
var value = liste[i][1];
}
}
var valueTotalS = parseInt(valueTotal) + parseFloat(value);
$('#participantEventTicketDiscountValue').html(value.toFixed(2));
$('#participantEventTicketDiscountValueTotal').html(valueTotalS);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
ticket 1
<input type="checkbox" name="participantEventTicket[]" value="5" class="participantEventTicket" />
<br/>ticket 2
<input type="checkbox" name="participantEventTicket[]" value="10" class="participantEventTicket" />
<br/>Sume tickets: <span class="participantEventTicketSum" id="participantEventTicketSum">0.00</span>
<br/>Discount coupon
<input type="text" id="participantEventTicketDiscount" class="participantEventTicketDiscount">
<br/>Discount value <span id="participantEventTicketDiscountValue" class="participantEventTicketDiscountValue">0.00</span>
<br/>Discount value sum <span id="participantEventTicketDiscountValueTotal" class="participantEventTicketDiscountValueTotal">0.00</span>
</form>
Slawotu,
Please check this fiddle
You had couple errors:
$('.participantEventTicket:checked').each(function () { totalPrice += parseFloat($(this).val(), 10);});
// you supposed to take $(this).val()
You didn't put calculation of total Price when you entered discount and changed you ticket:
$('.participantEventTicketDiscountValueTotal').html(totalPrice + value);
Forgot but brackets:
liste[0] = [['ABB'], -5];
liste[1] = [['BBC'], -10];
You compared 2 different objects using === instead use ==
if (liste[i][0] == code)
Declare val on top of the file, don't declare inside if statement.
var value = 0;
I'm looking for jQuery code which will list all classess from inputs and display how many times every class (in this case class=value) is selected.
html schema:
<input type="checkbox" name="t1" class="a1" value="a1">
<input type="checkbox" name="t1" class="a2" value="a2">
<input type="checkbox" name="t1" class="a3" value="a3">
<input type="checkbox" name="t2" class="a1" value="a1">
<input type="checkbox" name="t2" class="a2" value="a2">
<input type="checkbox" name="t2" class="a3" value="a3">
...
<input type="checkbox" name="t9" class="a99" value="a99">
example of expected result:
a1 - 2
a2 - 0
a3 - 0
a99 - 0
Try
var map = {};
$('input[type=checkbox]').each(function () {
if (this.checked) {
map[this.className] = (map[this.className] || 0) + 1;
} else {
map[this.className] = map[this.className] || 0;
}
});
console.log(map)
Demo: Fiddle
You could try something like this:
var checked = new Array();
$("input[type=checkbox]").each( function() {
var cl = $(this).attr('class');
if (typeof(checked[cl]) == "undefined") checked[cl] = 0;
if ($(this).is(':checked')) checked[cl]++;
});
After this, you will have variable checked containing all checkbox classes, with number of checked boxes for each class.
Let me know if this works for you.
Fiddle: http://jsfiddle.net/smBSw/1/
var resultList = {}
$('input:checkbox').each(function () {
var result = resultList[this.className] || 0;
if (this.checked) {
result++;
}
resultList[this.className] = result;
});
console.log(resultList)
console.log(JSON.stringify(resultList));
You can use like :
var className = [];
$("#btn").click(function () {
$("#result").html("");
$("input[class^=a]").each(function () {
className.push($(this).attr("class"));
});
className = jQuery.unique(className);
for (i = 0; i < className.length; i++) {
var count = 0;
$("." + className[i]).each(function () {
if (this.checked) {
count++;
}
});
$("#result").append(
"<br/><span> " +
"className: " + className[i] + ", " +
"count :" + count +
"</span>"
);
}
});
demo fiddle
Basically you will need to iterate through these inputs.. but you will need a place to save the counts
$(".checkboxes").on("change", "input", function() {
var results = {"a1": 0, "a2": 0, "a3": 0};
$(".checkboxes input").each(function(i, checkbox) {
if (!$(checkbox).prop("checked")) {
return;
}
results[$(checkbox).val()] = results[$(checkbox).val()] + 1;
});
var resultsToAppend = '';
$.each(results, function(key, value) {
resultsToAppend += '<li>' + key + ' : ' + value + '</li>';
});
$(".results").html(resultsToAppend);
});
Here's a fiddle
I running a similar script to this script from fiddle
http://jsfiddle.net/QmTNZ/2/
I tried to modify it to work with my table.
Here is the link to the table on the product page
http://styleso1.nextmp.net/dev/shop/safari-pu-sleeve-jacket.html
I need it to calculate the Qty ( input box, Column 4) X the unit price ( Column 5 ) and show the sum in column 6
How would i modify the JS to do this?
Here is what i have for the JS
$(function(){
function ca(){
var $overall = 0;
$("tr.sum").each(function() {
var $qnt = $(this).find(".qty");
var $price = $(this).find("td").eq(1);
console.log($qnt + " | " + $price);
var sum = parseFloat($price.text()) * parseFloat($qnt.val());
$(this).find(".a-center1").text(sum);
$overall += sum;
});
$("#total").text($overall);
}
$(function() {
ca();
$('input.qty').bind('change keyup',function(){ca();});
});
Any Help would be very appreciated
Try this
$("tr.sum").each(function() {
var $qnt = $(this).find(".qty");
var $price = $(this).find("td:eq(4)").find('.price');
console.log($qnt + " | " + $price);
var pri = $price.text();
pri = pri.replace('$', '');
var sum = parseFloat(pri) * parseFloat($qnt.val());
$(this).find("td").eq(5).text('$' + sum);
$overall += sum;
});
$("#total").text('$' +$overall);
Check Fiddle
You can save some DOM searching and text parsing by doing some simple things like adding the unit price as a data attribute to the row and retrieving it with jQuery data() method
HTML
<tr class="sum" data-unit_price="10.00">
JS
function ca(){
var $overall = 0;
$("tr.sum").each(function() {
var $row=$(this);
var $qnt = $(this).find(".qty");
var cost = $row.data('unit_price');
var sum = cost * parseFloat($qnt.val());
$(this).find("td").eq(5).text('$' +sum);
$overall += sum;
});
$("#total").text('$' +$overall);
}
$(function() {
ca();
$('input.qty').bind('change keyup', ca);
});
DEMO: http://jsfiddle.net/Jk976/3/