Disabling checkbox works, but it's not being processed on onchange - javascript

When the checkbox is set to false by the javascript function, the next function doesn't seem to know it has been set to false, it just ignores it.
HTML
<input type="checkbox" name="accs" id="50" class="arms"/>Arm 1: $50<br/>
<input type="checkbox" name="accs" id="60" class="arms"/>Arm 2: $60<br/>
<input type="checkbox" name="accs" id="70" class="neck"/>Neck 1: $70<br/>
<input type="checkbox" name="accs" id="80" class="neck"/>Neck 2: $80<br/>
<div id="total">$500</div>
Javascript: This function disables the checkbox according to the input class
$('.arms, .neck').change(function(){
var myClass = $(this).attr('class');
$('.'+myClass).not(this).prop('checked', false);
});
Javascript next function: The block of code that processes the action if the checkbox is either enabled or disabled
var input = document.getElementsByTagName("input");
var total = document.getElementById("total");
var prev;
for(i=0;i<input.length;i++){
input[i].onchange = function(){
if (this.type != 'text'){
if(this.checked){
$("#total").fadeOut(300);
$("#total").fadeIn(300);
prev=parseFloat(total.innerHTML.replace(/[^0-9\,]+/g,"")) + parseFloat(this.id);
total.innerHTML = "$" + prev.formatMoney(0, ',', '.');
}else{
$("#total").fadeOut(300);
$("#total").fadeIn(300);
prev=parseFloat(total.innerHTML.replace(/[^0-9\,]+/g,"")) - parseFloat(this.id);
total.innerHTML = "$" + prev.formatMoney(0, ',', '.');
}
}
}
}
After clicking all the checkbox you realize that it won't go back to the original price (500) but keeps on adding up.
Fiddle
The reason I haven't used radio is because the form must send the same 'input name' for all the options

I set up a fiddle here: http://jsfiddle.net/MarkSchultheiss/r6MXA/2/
Using this markup:
<input type="checkbox" name="accs" icost="50" class="arms" />Arm 1: $50
<br/>
<input type="checkbox" name="accs" icost="60" class="arms" />Arm 2: $60
<br/>
<input type="checkbox" name="accs" icost="70" class="neck" />Neck 1: $70
<br/>
<input type="checkbox" name="accs" icost="80" class="neck" />Neck 2: $80
<br/>
<div id="total">$500</div>
and this code:
var items = $('input.arms[type="checkbox"], input.neck[type="checkbox"]');
items.change(function () {
var myClass = $(this).attr('class');
$('.' + myClass).not(this).prop('checked', false);
var total = $('#total');
var totalcost = 0;
total.fadeOut(300);
items.filter(':checked').each(function (i) {
var cost = $(this).attr('icost');
totalcost = totalcost + parseFloat(cost);
});
total.text("$" + totalcost + ".00"); // fix your format here as needed
total.fadeIn(300);
});
EDIT: manage the whole check/uncheck cycle thing with a base on the current value in the text total area.
var items = $('input.arms[type="checkbox"], input.neck[type="checkbox"]');
// get the initial total and store in a data for use later (resets as needed)
var total = $('#total');
total.data("currentvalue", parseFloat(total.text().replace(/[^0-9\,]+/g, "")));
items.change(function () {
var currenttotal = total.data("currentvalue");
var myClass = $(this).attr('class');
var thisGroup = $('.' + myClass);
var notme = $('.' + myClass + ':checked').not(this);
var notmeCost = (notme.length ? notme.attr('icost') : ($(this).is(':checked') ? 0 : $(this).attr('icost')));
notme.prop('checked', false);
currenttotal = currenttotal - notmeCost;
total.fadeOut(300);
thisGroup.filter(':checked').each(function (i) {
var cost = $(this).attr('icost');
currenttotal = currenttotal + parseFloat(cost);
});
total.data("currentvalue", currenttotal);
total.text("$" + currenttotal + ".00"); // fix your format here as needed
total.fadeIn(300);
});

Related

How to calculate numbers (total) based on the checked checkboxes using jQuery?

I have a a few checkboxes on my page and each checkbox has a data-price attribute.
The data-price represents a price of an item.
I'm trying to calculate a total value based on the checked boxes that is checked and also make sure the deduct the value of the UN-CHECKED checkboxes from the total value.
So far I have done this:
https://jsfiddle.net/523q4n72/1/
The issue that I have is that when I add up the price, it works fine but when I uncheck a checkbox, the total value jumps to minus and it does some strange calculations.
To test it, just check the checkboxes and uncheck one or two of them to see the issue.
$(document).on("click", ".checks", function() {
if ($(this).prop('checked') == true) {
var price = $(this).attr("data-price");
var tots = $('#tots').html();
var setPrice = Number(price) + Number(tots);
var ffp = Math.round(setPrice * 100) / 100;
$('#tots').text(ffp);
} else if ($(this).prop('checked') == false) {
var price = $(this).attr("data-price");
var tots = $('#tots').html();
var setPrice = Number(price) - Number(tots);
var ffp = Math.round(setPrice * 100) / 100;
$('#tots').text(ffp);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>£<span id="tots">0.00</span></h4>
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
DRY - Don't repeat yourself.
In this case Loop each checked checkbox.
I have extracted the function so we can call it when changed AND when loading in case a checkbox was already checked
function calc() {
var tots = 0;
$(".checks:checked").each(function() {
var price = $(this).attr("data-price");
tots += parseFloat(price);
});
$('#tots').text(tots.toFixed(2));
}
$(function() {
$(document).on("change", ".checks", calc);
calc();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>£<span id="tots">0.00</span></h4>
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" checked name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
Alternative way of calling and initialising
$(".checks").on("change", calc).change();
Just change:
var setPrice = Number(price) - Number(tots);
to
var setPrice = Number(tots) - Number(price);
and it should work fine. The issue is occurring as you are trying to subtract the total price from the checked element price.
UPDATED FIDDLE
A better idea is to recalculate the total sum each time from the currently checked elements (instead of adding or subtracting based on the current element)
And it is better to target the change event instead of the click.
$(document).on("change", ".checks", function() {
var checked = $('.checks:checked'),
sum = checked.get().reduce(function(prev, item) {
return prev + parseFloat(item.getAttribute('data-price'));
}, 0);
$('#tots').text( sum.toFixed(2) );
});
Updated fiddle at https://jsfiddle.net/523q4n72/3/
You were subtracting the total from the number clicked. Line 19 should read
var setPrice = Number(tots) - Number(price);
rather than
var setPrice = Number(price) - Number(tots);
:)
You must change Number(price) - Number(tots) to Number(tots) - Number(price) to have the right equation.
You redeclare everything every time, why not declare outside of the conditions ?
var price = 0;
var tots = "";
var setPrice = 0;
var ffp = 0;
$( document ).on( "click", ".checks", function() {
if ($(this).prop('checked')==true){
price = $(this).attr("data-price");
tots = $('#tots').html();
setPrice = Number(price) + Number(tots);
ffp = Math.round(setPrice * 100) / 100;
$('#tots').text(ffp);
} else if ($(this).prop('checked')==false){
price = $(this).attr("data-price");
tots = $('#tots').html();
setPrice = Number(tots) - Number(price);
ffp = Math.round(setPrice * 100) / 100;
$('#tots').text(ffp);
}
});
Here you go with a solution https://jsfiddle.net/523q4n72/5/
var total = 0;
$(document).on("click", ".checks", function() {
if ($(this).prop('checked') == true) {
total += Number($(this).data("price"));
} else if ($(this).prop('checked') == false) {
total -= Number($(this).data("price"));
}
$('#tots').text(Math.round(total * 100) / 100);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>£<span id="tots">0.00</span></h4>
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
Hope this will help you.
Honestly I would just approach it a different way then you have. When .checks is clicked, iterate over each checkbox and add the values of those checked (updated fiddle). It seems much easier to read, imo.
$( document ).on( "click", ".checks", function() {
//reset totals on each click
var total = 0;
//Add checked totals
$('.checks').each(function(){
if($(this).prop('checked') == true) total += $(this).data('price');
});
//Update new total
$('#tots').html(total.toFixed(2));
});
Instead of looking at the item that is (un)checked, loop the ones that are checked using the :checked selector.
It simplifies your code:
$('.checks').on('change', function() {
var total = 0;
$('.checks:checked').each(function() {
total += $(this).data('price');
});
$('#tots').text( total.toFixed(2) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>£<span id="tots">0.00</span></h4>
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
var setPrice = 0;
$( document ).on( "click", ".checks", function() {
if ($(this).prop('checked')==true){
var price = $(this).attr("data-price");
var tots = $('#tots').html();
var setPrice = Number(price) + Number(tots);
var ffp = Math.round(setPrice * 100) / 100;
$('#tots').text(ffp);
}else if ($(this).prop('checked')==false){
var price = $(this).attr("data-price");
var tots = $('#tots').html();
var setPrice = Number(tots) - Number(price);
var ffp = Math.round(setPrice * 100) / 100;
$('#tots').text(ffp);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>£<span id="tots">0.00</span></h4>
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94

Add values from input to array on button click

I have 3 bootstrap sliders, which are basically input fields. The values of these sliders get displayed into an input box, and below that a price value is displayed. What I need to do is to save those 4 values to an array whenever a button is clicked. I managed to do this with the values hardcoded and without a button like this:
<li> <a class = "add-to-cart" href = "#" data-name = "Windows" data-price = "99.95" data-ram ="1" data-diskSpace="30" data-cpu="3">
<script>
$(".add-to-cart").click(function(event){
event.preventDefault(); // prevents the links from doing their default behaviour
var name = $(this).attr("data-name");
var price = Number($(this).attr("data-price"));
var ram = Number($(this).attr("data-ram"));
var diskSpace =Number($(this).attr("data-diskSpace"));
var cpu = Number($(this).attr("data-cpu"));
addItemToCart(name,price,1,ram,diskSpace,cpu);
displayCart();
});
var cart = [];
var Item = function (name,price,quantity,ram,diskSpace,cpu){
this.name = name;
this.price = price;
this.quantity = quantity;
this.ram = ram;
this.diskSpace = diskSpace;
this.cpu = cpu;
};
//addItemToCart(name,price,quantity)
function addItemToCart(name,price,quantity,ram,diskSpace,cpu){
for (var i in cart){
if(cart[i].name === name){
cart[i].quantity +=quantity;
saveCart();
return;
}
}
var item = new Item(name,price,quantity,ram,diskSpace,cpu);
cart.push(item);
}
</script>
This is my code for the values from the input box :
<input class="slider" id="ram" data-slider-id='ex1Slider' type="text" data-slider-min="0" data-slider-max="10" data-slider-step="1" />
<hr />
<input class="slider" id="diskSpace" data-slider-id='ex1Slider2' type="text" data-slider-min="0" data-slider-max="100" data-slider-step="10" />
<hr />
<input class="slider" id="cpu" data-slider-id='ex1Slider3' type="text" data-slider-min="0" data-slider-max="4" data-slider-step="1" />
<hr />
<input type="text" class="form-control" id="inputValue" value="0" />
</div>
Prijs:
<div id = "prijs">
</div>
<script>
var minSliderValue = $("#ram").data("slider-min");
var maxSliderValue = $("#ram").data("slider-max");
$('#ram').slider({
value : 0,
formatter: function(value) {
return 'RAM: ' + value + 'GB';
}
});
$('#diskSpace').slider({
value : 0,
formatter: function(value) {
return 'Disk Space: ' + value + 'GB';
}
});
$('#cpu').slider({
value : 0,
formatter: function(value) {
return 'CPU : ' + value + ' Cores';
}
});
// If You want to change input text using slider handler
$('#ram, #diskSpace, #cpu').on('slide', function(slider){
var ram = parseFloat($('#ram').val());
var diskSpace = parseFloat($('#diskSpace').val());
var cpu = parseFloat($('#cpu').val());
$("#inputValue").val("RAM="+ ram + "GB, Disk=" +diskSpace + "GB, Core="+cpu);
var totalPrice=(parseFloat(ram)*3.5 + parseFloat(diskSpace)*0.15+ parseFloat(cpu)*6.5).toFixed(2);
$("#prijs").html(totalPrice);
});
</script>
working jsfiddle for the sliders function: http://jsfiddle.net/umxhhqy4/8/

Javascript : function bind.click & for each checkbox

I have some combo box, every combo box have value and group by class & ID
<input type="checkbox" value="A" class="box-1" id="ID_1">
<input type="checkbox" value="B" class="box-1" id="ID_1">
<input type="checkbox" value="C" class="box-2" id="ID_2">
<input type="checkbox" value="D" class="box-2" id="ID_2">
If user click button, then check each box, if this checked, store value & ID to variable.
EDIT :
JS :
$('#button').bind('click', function() {
var box = '';
var p =0;
var count = document.getElementById("count").value; // for count total class checkbox
for(d=1; d <= count; d++){
p = 0;
$('.box-' + d).each(function(item){ // each box-1/2/3
if(this.checked){
if(p == 0)
{
var name = this.value.replace(/\s/g, '');
box += '&' + ($(this).attr('id')) + '=' + '&' + encodeURIComponent(name).toLowerCase());
p+=1;
alert(box);
}
else
{
var href = ($(this).attr('id')) + '=';
var name_2 = this.value.replace(/\s/g, '');
box += href + '&' + encodeURIComponent(name_2).toLowerCase());
p+=1;
}
}
});
}
alert(box);
//location = url;
});
example case :
the checked combo box is A & D
what i expect is &ID_1=&AID_2=&D ( this is different ID), if same ID = &ID_1=&A&D
when i try alert it's display nothing(''), but when i try alert(box) inside if( p== 0) it's have result 1&ID_1=A and 0&ID_2=&D.
Try check this here
change your code into like this
$('#button').bind('click', function() {
var boxval="";
//&ID_1=&AID_2=&D
$("input[class^='box-']").each(function(){
if($(this).is(':checked'))
{
boxval += $(this).attr('id') +'=&' + $(this).attr('value');
}
});
if(boxval !='')
alert(boxval)
else
alert("nothing will selected");
});
below is the working fiddle
https://jsfiddle.net/17hxsa9r/
You have declared box twice in your code
var box = '';
and
$('.box-' + d).each(function(box){ // each box-1/2/3
The box declared inside each() hides the outer box, therefore its value is not changed.
You need to name one of them differently.

jQuery - list input classess and get number of selected checkboxes

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

textbox values based on checkbox checked/unchecked

My problem is simple not so lengthy as looking like.
I have 7 textboxes having ids text1, text2, text3, text4 and text5, text6, text7 and one checkbox having id check. I am getting value of text1 and text2 by JSON as 10 and 20 and displaing total 30 in text7. Values of text4,text5 and text6 are empty that is these textboxes display "0". text3 and text4 will be autofilled based on checkbox.
When i checked the checkbox then "Points" will be autofilled in text3 and "100" will be autofilled in text4. Now total text7 will show 130. Values of text5 and text6 display "0". If i will write something let's say "10" in text5 and "20" in text6 then total text7 will show 160. If i uncheck the checkbox, then values of text3 and text4 will be removed and total will be changed acordingly.I am not able to know how to autofill text3 and text4 after checking the checkbox, any idea please?
index.jsp
$(document).ready(function() {
$("#combo1").change(function() {
$.getJSON(
'combo1.jsp',
{ combo1Val : $(this).val() },
function(data) {
var a = data.valueoffirsttextbox; //Got 10 from db
var b = data.valueofsecondtextbox; //Got 20 from db
var total = parseInt(a) + parseInt(b);
$("#combo2").val(data.name);
$("#text1").val(a)
$("#text2").val(b)
$("#text7").val(total); // here i am showing total 30 in text7
}
);
// when checkbox is unchecked text4 is not present
$("#text1, #text2, #text5, #text6").keyup(function() {// if any editing occurs
in these values then total will be changed accordingly
var a = $("#text1").val();
var b = $("#text2").val();
var c = $("#text5").val();
var d = $("#text6").val();
var total = parseInt(a) + parseInt(b) + parseInt(c) + parseInt(d);
$("#text7").val(total);// shows total with out text4's value
// when checkbox is checked then text4's value is added
$("#text1, #text2, #text4, #text5, #text6").keyup(function() {// if any editing
occurs in these values then total will be changed accordingly
var a = $("#text1").val();
var b = $("#text2").val();
var c = $("#text5").val();
var d = $("#text6").val();
//here text4 is added
var e = $("#text4").val();
var total = parseInt(a) + parseInt(b) + parseInt(c) + parseInt(d) + parseInt(e) ;
$("#text7").val(total);// show total with text4's value
});
});
});
<body>
<input type="checkbox" id=check"/>
<input type="text" id="text1"/>
<input type="text" id="text2"/>
<input type="text" id="text3"/>// how can i autofill "POINTS" in this
textbox after checking the checkbox?
<input type="text" id="text4" value="0"/>//how can i autofill "100" in this textbox
after checking the checkbox?
<input type="text" id="text5" value="0"/>
<input type="text" id="text6" value="0"/>
<input type="text" id="text7" value="0"/>// shows total of all values of above
textboxes except text3
</body>
You can check this jsFiddle: http://jsfiddle.net/Af6LP/1/ Modify it according to your needs.
Script
$(document).ready(function() {
$("#check").change(function() {
if ($(this).is(":checked")) $("#text4").val("100");
else $("#text4").val("0");
calculate();
});
$("#text1, #text2, #text5, #text6").keyup(function() {
calculate();
});
});
function calculate() {
var a = $("#text1").val();
var b = $("#text2").val();
var c = $("#text5").val();
var d = $("#text6").val();
var total = parseInt(a) + parseInt(b) + parseInt(c) + parseInt(d);
if ($("#check").is(":checked")) total += parseInt($("#text4").val());
$("#text7").val(total);
}​
HTML
<body>
<input type="checkbox" id="check"/><br/>
<input type="text" id="text1" value="10"/><br/>
<input type="text" id="text2" value="20"/><br/>
// how can i autofill "POINTS" in this textbox after checking the checkbox?
<input type="text" id="text3"/><br/>
//how can i autofill "100" in this textbox after checking the checkbox?
<input type="text" id="text4" value="0"/><br/>
<input type="text" id="text5" value="0"/><br/>
<input type="text" id="text6" value="0"/><br/>
// shows total of all values of above textboxes except text3<br/>
<input type="text" id="text7" value="30"/>
</body>​
Take a look at this solution:
demo jsBin
var a=10; // from database
var b=20; // from database
var e=0;
$("#text1").val(a); // read and set value
$("#text2").val(b); // read and set value
function getValues(){
a = parseInt($("#text1").val(), 10);
b = parseInt($("#text2").val(), 10);
var c = parseInt($("#text5").val(), 10);
var d = parseInt($("#text6").val(), 10);
doSomeCheck = $('#check').is(':checked') ? e=100 : e=0;
$('#text4').val(e);
$('#text3').val(a+b);
$("#text7").val(a+b+c+d+e);
}
getValues();
$("#check").change(function() {
getValues();
});
$("#text1, #text2, #text4, #text5, #text6").keyup(function() {
getValues();
if($(this).val() === '') $('#text7').val('...');
});
$(document).ready(function() {
$("#check").change(function() {
if ($(this).is(":checked")) $("#text4").val("100");
else $("#text4").val("0");
if ($(this).is(":checked")) $("#text3").val("POINTS");
else $("#text3").val("");
calculate();
});
$("#text1, #text2, #text5, #text6").keyup(function() {
calculate();
});
});
function calculate() {
var a = $("#text1").val();
var b = $("#text2").val();
var c = $("#text5").val();
var d = $("#text6").val();
var total = parseInt(a) + parseInt(b) + parseInt(c) + parseInt(d);
if ($("#check").is(":checked")) total += parseInt($("#text4").val());
$("#text7").val(total);
}
Just had to add another if/else for text3. Simple.

Categories