This is my code, here there are 6 checkboxes and it call 6 times and each time it make sum of both values, i am passing value like 10,10 than it should be a 20 but it returns 120,
How can I solve this problem?
jQuery('.pricefield input').each( function() {
var checkedValues = jQuery('input:checkbox:checked').map(function() {
str=this.value;
source_str = str.substr(str.indexOf("#"));
keywords = source_str.split (/[\D,]+/);
val1=keywords[1];
val2=keywords[2];
sum+=parseInt(val1, 10)+parseInt(val2, 10);
alert(sum);
pricefield_both(sum);
}).get();
});
You are not looking at the correct indexes and you need one more position after the #
Live Demo
$(function() {
$('.pricefield input').on("click",function () {
var sum=0;
$('input:checkbox:checked').each(function () {
var str=$(this).val().split("#")[1].split(",");
sum += (parseInt(str[0], 10) + parseInt(str[1], 10));
});
pricefield_both(sum); // assuming that function works
});
});
keywords = source_str.split (/[\D,]+/);
val1=keywords[1];
val2=keywords[2];
sum+=parseInt(val1, 10)+parseInt(val2, 10);
this code is not good!
try something like bellow!
keywords = source_str.split(/[\D,]+/);
val1 = +keywords[1];
val2 = +keywords[2];
sum += val1 + val2;
and I suggest you define the variables first so the local variable will not become globally accessble!
var str, source_str, keywords, val1, val2, sum;
the result is bellow:
var str, source_str, keywords, val1, val2, sum = 0;
jQuery('.pricefield input').each( function() {
var checkedValues = jQuery('input:checkbox:checked').map(function() {
str=this.value;
source_str = str.substr(str.indexOf("#"));
keywords = source_str.split (/[\D,]+/);
val1 = +keywords[1];
val2 = +keywords[2];
sum += val1 + val2;
alert(sum);
pricefield_both(sum);
}).get();
});
Related
I'm trying to reduce the amount of code I repeat.
Currently I have the below:
var item1H = $(".item-1").height();
var item1W = $(".item-1").height();
$(".item-1 .text").css('margin-left', -item1W/2);
$(".item-1 .text").css('margin-bottom', -item1H/2);
var item2H = $(".item-2").height();
var item2W = $(".item-2").height();
$(".item-2 .text").css('margin-left', -item2W/2);
$(".item-2 .text").css('margin-bottom', -item2H/2);
I'm looking to put this into a for loop where the variable number would count up to whatever number I needed it to stop.
You can make function like this and use whenever you want
toSetMargin(".item-2")
toSetMargin(".item-2")
function toSetMargin(objStr){
var widthTmp = $(objStr + ' .text').height();
var heightTmp = $(objStr + ' .text').height();
obj.css('margin-left', -widthTmp/2);
obj.css('margin-bottom', -heightTmp/2)
}
This code not impact any other code.
You could use $('[class^="item-"]') to get all the elements that have a class that starts with item-, and the loop over them
$('[class^="item-"]').each(function(){
var $elem = $(this);
var item1H = $elem.height();
var item1W = $elem.width();
$elem.find('.text').css({'margin-left': -item1W/2,'margin-bottom':-item1H/2});
});
Ooh boy, one of these problems. This should help (untested):
for(i=1;i<=STOPPING_NUMBER;i++){
window["item"+i+"H"] = $(".item-"+i).height();
window["item"+i+"W"] = $(".item-"+i).width(); //Was height, accident?
$(".item-"+i+" .text").css('margin-left', 0-window["item"+i+"W"]/2); //Hope this works lol
$(".item-"+i+" .text").css('margin-bottom', 0-window["item"+i+"H"]/2);
}
Guessing these lines:
var item1W = $(".item-1").height();
var item2W = $(".item-2").height();
Should have been:
var item1W = $(".item-1").width();
var item2W = $(".item-2").width();
You could do something like:
function setCSS(item,attr,val) {
$(item +" .text").css(attr, (val * -1)/2);
}
var i, max = 10;
for(i=1;i<=max;i++) {
setCSS(".item-"+ i,"margin-left",$(".item-"+ i).width());
setCSS(".item-"+ i,"margin-bottom",$(".item-"+ i).height());
}
Or something less flexible within the function:
function setCSS(item,w,h) {
$(item +" .text").css("margin-left", (w * -1)/2);
$(item +" .text").css("margin-bottom", (h * -1)/2);
}
var i, max = 10;
for(i=1;i<=max;i++) {
setCSS(".item-"+ i,$(".item-"+ i).width()),$(".item-"+ i).height());
}
Something like this should be pretty acceptible in your case, I guess:
for (var i = 1, len = someN; i < len; i++) {
var $item = $('.item-' + i);
$item.find('.text').css({
'margin-left': -$item.width() / 2,
'margin-bottom': -$item.height() / 2
});
}
I make a dynamic form, if i delete a row then in loop result is NaN of the deleted element i want when i delete element its 0 value pass not NaN. Like i delete 5th element when 1=5 it shows NaN. How to remove this error and instead 0 will be add in sum value, how i do?
$("body").on('change', '.quantity', function() {
var that = $(this);
if ($('#itemcounter').val()==""){
$('#itemscounter').val("1");
var counter=$('#itemscounter').val();
var quantity=$('#quantity').val();
var unitprice=$('#unitprice').val();
var linetotal=quantity*unitprice;
that.parent().find('.linetotal').val(linetotal)
$("#invoicetotalamount").val(+linetotal)
var discount=document.getElementById('discount').value ;
var discountamount= discount/100 * linetotal;
var amount=linetotal-discountamount;
$("#balanceamount").val(+amount);
} else {
var counter=$('#itemscounter').val();
var quantity=$('#quantity').val();
var unitprice=$('#unitprice').val();
var linetotal=quantity*unitprice;
$('#linetotal').val(+linetotal);
var sum=linetotal;
for (i = 2; i <=counter; i++) {
var quantity=parseFloat($('#quantity' + i).val());
var unitprice=parseFloat($('#unitprice' + i).val());
var linetotal=quantity*unitprice;
$('#linetotal' + i).val(+linetotal);
alert(sum);
sum=+sum +(+(linetotal));
}
$("#invoicetotalamount").val(+sum);
var discount=document.getElementById('discount').value ;
var discountamount= discount/100 * sum;
var amount=sum-discountamount;
$("#balanceamount").val(+amount);
}
});
Check the value if its a number like this:
var quantity=parseFloat($('#quantity' + i).val());
if(isNaN(quantity)){
quantity=0;
}
you can check it with if else loop for dynamic data:
var str_val = $('#itemscounter').val();
if(str_val == NaN){
str_val =0; //use str_val at the place you want
alert(str_val);
}
You can check to see if it's NaN
var quantity = !isNaN($('#quantity' + i).val()) ? parseFloat($('#quantity' + i).val(), 2) : 0;
I'm trying to populate select box using value from input text. So far I've been doing good in populating the select box. But the problems came when I change the input field into another value. The select box won't reset the array instead of adding the option value in the end of array. Here's my code:
HTML:
<input type="text" name="ttc_list" id="ttc_list" />
<select name="priority_list" id="priority_list">
<option value="">Choose TTC First...</option>
</select>
Javascript:
$(document).ready(function(){
$("select#priority_list").attr("disabled","disabled");
$('input[name="ttc_list"]').change(function() {
var arr = [];
arr.length = 0;
var ttc = $("#ttc_list").val();
if(ttc == 100 || ttc == 101)
{
var prty100_Start = 40;
var prty100_End = 80;
while(prty100_Start < prty100_End+1){
arr.push(zeroPad(prty100_Start++,2));
}
}
else
{
var prty200_Start = 1;
var prty200_End = 5;
while(prty200_Start < prty200_End+1){
arr.push(zeroPad(prty200_Start++,2));
}
}
var selectOptions = {
100: arr,
101: arr,
200: arr,
204: arr,
210: arr
}
$("select#priority_list").removeAttr("disabled");
console.log($(this).val());
if(selectOptions[$(this).val()])
{
console.log(selectOptions[$(this).val()]);
$.each(selectOptions[$(this).val()], function() {
$('select[name="priority_list"]').append('<option>' + this + '</option>');
});
}
});
});
function zeroPad(num, numZeros) {
var n = Math.abs(num);
var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
var zeroString = Math.pow(10,zeros).toString().substr(1);
if( num < 0 ) {
zeroString = '-' + zeroString;
}
return zeroString+n;
}
Example: When user filled '100' in input text, it works fine in populating select box from '40' to '80', but when user changes the input text to '200' without refreshing the page, the select box show options from '40' to '80' and '01' to '05' instead of only '01' to '05'.
Expected result: When user changes the input text to '200' without refreshing the page, the select box shows options only from '01' to '05'
Here's my working demo http://jsfiddle.net/danc32/6UqYS/1/.
Where should I put my arr.length = 0 to reset my array?
Because you are using .append('<option>' + this + '</option>');, every time you change you add the new options to the existing list. Instead you could use:
.html('<option value="">Choose TTC First...</option>'); // remove old options
to reset the select and remove the old options, then use:
.append('<option>' + this + '</option>'); // add new options
to add the new ones.
See this JSFiddle for complete code.
You need to clear the contents of the select element before adding new items... also there is no need to recreate the selectOptions object within the change handler.. it is a static object so it can be created only once as given below
$(document).ready(function () {
var $priority_list = $("#priority_list").prop("disabled", true);
var selectOptions = {};
var arr_40_80 = arrays(40, 80);
selectOptions['100'] = arr_40_80;
selectOptions['101'] = arr_40_80;
var arr_1_5 = arrays(1, 5);
selectOptions['200'] = arr_1_5;
selectOptions['204'] = arr_1_5;
selectOptions['210'] = arr_1_5;
$('input[name="ttc_list"]').change(function () {
var ttc = $(this).val(), arr = selectOptions[ttc];
$priority_list.prop("disabled", false).empty();
if (arr) {
$.each(arr, function () {
$priority_list.append('<option>' + this + '</option>');
});
}
});
});
function arrays(start,end){
var arr = [];
while (start <= end) {
arr.push(zeroPad(start++, 2));
}
return arr;
}
function zeroPad(num, numZeros) {
var n = Math.abs(num);
var zeros = Math.max(0, numZeros - Math.floor(n).toString().length);
var zeroString = Math.pow(10, zeros).toString().substr(1);
if (num < 0) {
zeroString = '-' + zeroString;
}
return zeroString + n;
}
Demo: Fiddle
I have used a jsFiddle that I found on another question on here that will work perfectly if I can get the subtotal to multiply instead of addition.
I am sure this is a really easy fix, but I'm struggling to make the change.
Can someone help me please?
Thank you in advance
http://jsfiddle.net/77uxK/48/
$(document).ready(function(){
var sum = 0;
function calcSum(prevVal){
sum = sum - prevVal + (this.value/1);
return sum;
}
var subAmt = $("#sub"), taxAmt = $("#tax"), totAmt = $("#total");
$(".val").each(function(){
var prevVal = this.value/1, self = this;
$(this).keyup(function(){
subAmt.val(calcSum.call(self, prevVal));
totAmt.val(sum + sum*parseFloat(taxAmt.val()/100));
prevVal = self.value;
});
});
});
just change the function to
function calcSum(prevVal) {
var val1 = $('#val1').val();
var val2 = $('#val2').val();
sum = parseInt(val1) * parseInt(val2); // parseFloat based on your need change it
return sum;
}
jsfiddle link
I am trying to find the sum of checkbox values (23.75 and 142.75)
Poaten
Checkbox1: 2012-01-17, Porti, 1.760, 23.75
Checkbox2: 2012-01-17, Kopien, 10.560, 142.55
Checkbox3: 2012-01-17, Honorar, 33.600, 453.60
Checkbox4: 2012-01-17, Telefon, 0.640, 8.65
The output is in "Restbetrag". I used the following function but I receive the sum of primary key's value of selected checkbox items in "Posten".
In posten I see four values for each checkbox which are separated by comma. Where should I start to have the 4th value of each clicked checkbox (23.75, 142.55...)? Could you please advice where to find a similar solutions?
Thanks
mpol
function showTotal() {
document.frechnungenadd.x_Restbetrag.value = '';
//document.write("test");
var sum = 0;
var elements = document.getElementsByName("x_Posten[]");
for (i=0;i < elements.length;i++) {
if (elements[i].checked) {
sum = sum + +elements[i].value;
}
}
document.frechnungenadd.x_Restbetrag.value = sum;
}
Not sure if this is what you are looking for...
if (elements[i].checked) {
var myarr = elements[i].value.split(",");
sum += parseFloat(myarr[3]);
}
I solved my problem. Thanks for your support. Here your the code for solution.
Regards
mpol_ch
function showTotal() {
document.frechnungenadd.x_Summe.value = '';
document.frechnungenadd.x_MwSt.value = '';
//document.write("test");
var Summe = 0;
var MwSt = 0
var splitted
var elements = document.getElementsByName("x_Posten[]");
for (i=0;i < elements.length;i++) {
if (elements[i].checked) {
splitted = elements[i].nextSibling.nodeValue.split(",");
MwSt = MwSt+ + parseFloat(splitted[2]);
Summe = Summe+ + parseFloat(splitted[3]);
}
}
document.frechnungenadd.x_MwSt.value = MwSt.toFixed(2);
document.frechnungenadd.x_Summe.value = Summe.toFixed(2);
}
setInterval('showTotal()',1000);