Sub total and total auto compute - javascript

I just need the following:
subtotal = sum(product1,product2)
total = sum(subtotal,vat)
from code
$('input').keyup(function(){
var v = this.value, el = $(this);
if(!isNaN(v)){
var ov = el.siblings('.valid').val();
el.siblings().last().val(v*ov);
$(this).removeClass('nope').trigger('totalChange');
} else {
$(this).addClass('nope');
}
});
$(document).on('totalChange', function(){
var val1 = parseFloat($('#vat_zero_re').val(), 10);
var val2 = parseFloat($('#ve_subtotal').val(), 10);
$('#total').val(val1+val2);
});
source code : http://jsfiddle.net/4c0epamc/

Check this fiddle
Javascript
$('input').keyup(function(){
var v = this.value, el = $(this);
if(!isNaN(v)){
var ov = el.siblings('.valid').val();
el.siblings().last().val(v*ov);
$(this).removeClass('nope').trigger('totalChange');
} else {
$(this).addClass('nope');
}
});
$(document).on('totalChange', function(){
var valx=parseFloat($('#peza_locator').val(), 10);
var valy = parseFloat($('#peza_facilities').val(), 10);
$('#ve_subtotal').val(valx+valy);
var val1 = parseFloat($('#vat_zero_re').val(), 10);
var val2 = parseFloat($('#ve_subtotal').val(), 10);
$('#total').val(val1+val2);
});
In the fiddle that you specified no jquery was linked and in my fiddle to calculate the sub total i used 2 new variables named valx and valy.. check it..

Related

alter array object property then save back to localStorage?

I'm doing a cart and I want to increment the qty if the item_id exising in localStorage.
<button data-item_id="1" data-item_name="cake" data-item_price="2 dollar">Add to cart</button>
Not sure why my below code doesn't work, it added a new object instead of increment the qty value.
$(function(){
$('button').click(function(){
var item_id = $(this).attr('data-item_id');
var item_name = $(this).attr('data-item_name');
var item_price = $(this).attr('data-item_price');
var arr = JSON.parse(localStorage.getItem('cart')) || [];
var obj = {};
if(arr.length === 0){ // first time insert
obj.item_id = item_id;
obj.item_name = item_name;
obj.item_price = item_price;
obj.item_qty = 1;
}else{
$(arr,function(i){
//doesn't work here
obj.item_qty[i] = parseInt(this.qty) + 1;
});
}
arr.push(obj);
localStorage.setItem('cart',JSON.stringify(arr));
});
});
debug for few hours couldn't solved.
Use {} instead of [] making the arr contain one object per item_id and each object will get 1 added to the qty each time it is called. There is no remove in this code
$(function(){
$('button').on("click",function(e){
var item_id = $(this).data("item_id");
var item_name = $(this).data("item_name");
var item_price = $(this).data("item_price");
var cart = JSON.parse(localStorage.getItem('cart')) || {};
var currentObj = cart[item_id];
if(currentObj){
currentObj.qty++; // increase the qty by one
}
else { // item_id had not been stored before, create it
cart[item_id]= {
"item_name" :item_name,
"item_price":item_price,
"item_qty" :1
}
}
localStorage.setItem('cart',JSON.stringify(cart));
});
});
Then you have to do like this:
$(function(){
$('button').click(function(){
var item_id = $(this).attr('data-item_id');
var item_name = $(this).attr('data-item_name');
var item_price = $(this).attr('data-item_price');
var arr = JSON.parse(localStorage.getItem('cart')) || [];
var obj = {};
obj.item_id = item_id;
obj.item_name = item_name;
obj.item_price = item_price;
obj.item_qty = 1;
detectchange = 'no';
$.each(arr,function(i){
if(this.item_id == obj.item_id){
this.item_qty = parseInt(this.item_qty) + 1; detectchange = 'yes'; }
});
if(detectchange =='no'){
arr.push(obj); }
localStorage.setItem('cart',JSON.stringify(arr));
});
});

Run jQuery code after AJAX jQuery load()

How can i run the below code only after the code 1 has load all its content from the external page ?
jQuery Script tried
//filters
$(window).bind("load", function() {
$(".filters li").on("click", function () {
id = ($(this).data("id")+'').split(',');
filter = $(this).data("filter");
$("#hotel-list .box").hide();
id[0] == "all" && $("#hotel-list .box").show() || id.forEach(function(v){
$('#hotel-list .box[data-'+filter+'*="'+v.trim()+'"]').show();
});
return false;
});
<!-- Count Star Rating -->
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
$('.total-three').text(three_stars);
$('.total-four').text(four_stars);
$('.total-five').text(five_stars);
var totals = three_stars + four_stars + five_stars + two_stars;
$('.totals').text(totals);
<!-- Count Board -->
var board_no = $("article[data-board*='No']").length
var board_ro = $("article[data-board*='Room']").length
var board_bb = $("article[data-board*='Breakfast']").length;
var board_fb = $("article[data-board*='Full Board']").length
var board_hb = $("article[data-board*='Half']").length
var board_ai = $("article[data-board*='All']").length
var board_sc = $("article[data-board*='Self']").length
$('.total-ro').text(board_ro);
$('.total-bb').text(board_bb);
$('.total-fb').text(board_fb);
$('.total-hb').text(board_hb);
$('.total-ai').text(board_ai);
$('.total-sc').text(board_sc);
var total = board_ro + board_bb + board_fb + board_hb + board_ai + board_sc + board_no;
$('.total').text(total);
//Fix broken images
fixBrokenImages = function( url ){
var img = document.getElementsByTagName('img');
var i=0, l=img.length;
for(;i<l;i++){
var t = img[i];
if(t.naturalWidth === 0){
//this image is broken
t.src = url;
}
}
}
window.onload = function() {
fixBrokenImages('images/noimg.png');
}
});
And the jQuery AJAX code is:
var datastring = location.search; // now you can update this var and use
$("#hotel-list").load("Rezults2.php"+ datastring + " #hotel-list> *");
So i need that the 1st codes to be executed only after the 2nd code has done its job ( from 3 to 9 secs )
ANy ideea on this ?
function runThisAfter() {
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
//etc...
}
$("#hotel-list").load("Rezults2.php", function(){ runThisAfter(); });
This will run "runThisAfter()" when load is complete.
Solution is:
$(document).ajaxComplete(function( event, xhr, settings ) {
// Your complete function here
});
Or in my Case full code:
$(document).ajaxComplete(function(event, xhr, settings) {
//Count STARS
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
$('.total-three').text(three_stars);
$('.total-four').text(four_stars);
$('.total-five').text(five_stars);
var totals = three_stars + four_stars + five_stars +
two_stars;
$('.totals').text(totals);
//COUNT BOARD
var board_no = $("article[data-board*='No']").length
var board_ro = $("article[data-board*='Room']").length
var board_bb = $("article[data-board*='Breakfast']").length;
var board_fb = $("article[data-board*='Full Board']").length
var board_hb = $("article[data-board*='Half']").length
var board_ai = $("article[data-board*='All']").length
var board_sc = $("article[data-board*='Self']").length
$('.total-ro').text(board_ro);
$('.total-bb').text(board_bb);
$('.total-fb').text(board_fb);
$('.total-hb').text(board_hb);
$('.total-ai').text(board_ai);
$('.total-sc').text(board_sc);
var total = board_ro + board_bb + board_fb + board_hb +
board_ai + board_sc + board_no;
$('.total').text(total);
//Fix broken images
fixBrokenImages = function(url) {
var img = document.getElementsByTagName('img');
var i = 0,
l = img.length;
for (; i < l; i++) {
var t = img[i];
if (t.naturalWidth === 0) {
//this image is broken
t.src = url;
}
}
}
window.onload = function() {
fixBrokenImages('images/noimg.png');
}
});
});

How do I style all elements with Javascript? No Jquery (2 examples in description)

I got 2 scripts written with Javascript. The script have to result the same, but they don't. How do I write the Jquery function .css() in Javascript, so I'll get the same results?
SCRIPT 1(NOT working):
numItems = 0;
function addItem() {
var menu = document.getElementById('menu');
var addLink = document.createElement('a');
var input = document.getElementById('input');
var text = input.value;
addLink.innerHTML = text;
menu.appendChild(addLink);
addLink.setAttribute('href', text+'.html');
numItems++;
var itemWidth = (100/numItems)+'%';
addLink.style.width = itemWidth;
}
SCRIPT 2(Working, BUT with jQuery!):
function addItem() {
var numItems = $("#menu a").length+1;
var itemLink = document.createElement('a');
var input = document.getElementById('itemName');
var text = input.value;
itemLink.innerHTML = text;
document.getElementById('menu').appendChild(itemLink);
itemLink.setAttribute('href',text+'.html');
var itemWidth = (100/numItems);
$("#menu a").css("width", itemWidth+"%");
}
(PS. I just want to know, to improve my Javascript knowledge and to know how the Jquery .css() function is build.)
You need to change the widht of all items
var numItems = 0;
function addItem() {
var menu = document.getElementById('menu');
var addLink = document.createElement('a');
var input = document.getElementById('input');
var text = input.value;
addLink.innerHTML = text;
menu.appendChild(addLink);
addLink.setAttribute('href', text + '.html');
numItems++;
var itemWidth = (100 / numItems) + '%';
var as = menu.querySelectorAll('a');
for (var i = 0; i < as.length; i++) {
as[i].style.width = itemWidth;
}
}
Demo: Fiddle

jQuery Uncaught TypeError: Object[object Object] has no method 'toFixed'

Hi Guys i encounter Problem on my program which says that i have no method 'toFixed' what is the meaning or what to do to fix this?
Here is MY javascript
<script type="text/javascript">
$(document).ready(function(){
$("#datepicker").kendoDateTimePicker({
format: "yyyy-MM-dd HH:mm:ss"
});
$("#supplier_list").kendoComboBox();
$(".code_select").kendoComboBox();
//automatic computation in rows
$('[id^=qty],[id^=price],#tin_number').on('change',function() {
var index = this.id.match(/\d+/)[0];
var qty = parseInt($('#qty'+index).val());
var price = parseFloat($('#price'+index).val());
var disc = $("#discount").val();
var total = 0;
$('#total'+index).val((qty * price ? qty * price : 0).toFixed(2));
var total = 0;
$('[id^=total]').each(function(index){
total+=parseFloat($(this).val()?$(this).val():0);
});
var totalAll = $('#sum_of_total').val(total.toFixed(2));
var vatable = 0;
var vatable_amt = 0;
var totalVat = 0;
var computeDisc = 0;
if($("#tin_number").val().length != 0){
vatable = total / 1.12;
vatable_amt = vatable * 0.12;
totalVat = vatable + vatable_amt;
}else{
totalVat = total;
}
$('#vatable').val(vatable.toFixed(2));
$("#vatable_amount").val(vatable_amt.toFixed(2));
var gtotal = $("#gtotal").val(totalVat.toFixed(2));
$("#total_amt_due").val(gtotal.toFixed(2));
// Here is the line of error uncaught TypeError : Object[object object] has no method'toFixed'
});
$("#discount").on('change',function(){
var totalSales = $("#gtotal").val();
var discountedAmt = $("#discount").val();
var computeTotalDisc = totalSales - discountedAmt;
$("#total_amt_due").val(computeTotalDisc.toFixed(2));
});
//AUTO ASSIGN TO SUPPLIER INFO
$('#supplier_list').bind('change', function(){
var var_add_category ='<?php echo site_url("purchaseorder_controller/supplier_details"); ?>';
$.ajax({
type:'POST',
url: var_add_category,
data:{ id: $(this).val() },
dataType:'json',
success:function(d){
var bankname = d['bankname'];
var bankbranch = d['bankbranch'];
$("[name=spaddress]").val(d['spaddr']);
$("[name=tin]").val(d['sptinno']);
$("[name=contactperson]").val(d['pricontactname']);
$("[name=contactnumber]").val(d['sptelno']);
$("[name=bank]").val(bankname + ' - ' + bankbranch);
$("[name=account_name]").val(d['bankacctname']);
$("[name=account_no]").val(d['bankacctno']);
}
});
});
$("[id^=code]").on('change',function(){
var index = this.id.match(/\d+/)[0];
var validate = $('#code'+index).val();
if(validate != ''){
$("#qty"+index).removeAttr('readonly');
$("#price"+index).removeAttr('readonly');
}
});
$("[id^=code]").on('change',function(){
var index = this.id.match(/\d+/)[0];
var validate = $('#code'+index).val();
if(validate == ''){
$("#qty"+index).prop('readonly', true);
$("#price"+index).prop('readonly', true);
}
What to do pls help me guys thank you for the help in advance
gtotal is a jQuery object, not a number ?
var gtotal = $("#gtotal").val(totalVat.toFixed(2)); // returns jQuery object
$("#total_amt_due").val(gtotal.toFixed(2)); // that has no toFixed()
try:
var gtotal = totalVat.toFixed(2);
$("#gtotal, #total_amt_due").val(gtotal);
Try this:
var gtotal = +$("#gtotal").val(totalVat.toFixed(2)).val();
Then gtotal is number.
Also, you can't calculate a number that has already been .toFixed()
so you can do:
$('#vatable').val(vatable.toFixed(2));
$("#vatable_amount").val(vatable_amt.toFixed(2));
var gTotal = totalVat;
$("#gtotal").val(totalVat.toFixed(2));
$("#total_amt_due").val(gtotal.toFixed(2));
but you can't do:
var gTotal = totalVat.toFixed(2); //pretend this equaled 1000.00
var total_amt_due = gTotal + 1.toFixed(2);// this would give you 1000.001.00
or
var total_amt_due = total_amt_due.toFixed(2);//this would give you the object no method toFixed error

Javascript, trying to get conversion average

I have a script that is setting conversion rates depending on input boxes (works fine), however I now want to get an average of these rates.
My Code is
var avg1 = $('#conversion1').text();
var avg2 = $('#conversion2').text();
var avg3 = $('#conversion3').text();
var avg4 = $('#conversion4').text();
var avg5 = $('#conversion5').text();
var avg6 = $('#conversion6').text();
var sumavg = (avg1 + avg2 + avg3 + avg4 + avg5 + avg6) / 6;
sumavg = Math.round(sumavg*Math.pow(10,2))/Math.pow(10,2);
$('#conversion7').html(sumavg);
The id conversion1,2 etc have a number from 0-100 (the conversion rate). However whenever I run this script I get all sorts of crazy numbers for the average (sumavg or id conversion7). I do not know why! I should also note that this bit of code is inside of the function doing the conversion for each day which works fine.
See below for entire snippet:
// Conversion Rate
$.fn.sumConv = function(customers) {
var sum = 0;
var val = 0
this.each(function() {
if ( $(this).is(':input') ) {
val = $(this).val();
} else {
val = $(this).text();
}
customersval = $(customers).val();
sum = (customersval/val) * 100;
//sum += parseFloat( ('0' + val).replace(/[^0-9-\.]/g, ''), 10 );
sum = Math.round(sum*Math.pow(10,2))/Math.pow(10,2);
if(sum=="Infinity" || sum=="NaN") sum=0;
});
// do average
var avg1 = $('#conversion1').text();
var avg2 = $('#conversion2').text();
var avg3 = $('#conversion3').text();
var avg4 = $('#conversion4').text();
var avg5 = $('#conversion5').text();
var avg6 = $('#conversion6').text();
var sumavg = (avg1 + avg2 + avg3 + avg4 + avg5 + avg6) / 6;
sumavg = Math.round(sumavg*Math.pow(10,2))/Math.pow(10,2);
$('#conversion7').html(sumavg);
return sum;
};
$('input#foot1').bind('keyup', function() {
$('#conversion1').html( $('input#foot1').sumConv('input#customers1') );
});
$('input#customers1').bind('keyup', function() {
$('#conversion1').html( $('input#foot1').sumConv('input#customers1') );
});
$('input#foot2').bind('keyup', function() {
$('#conversion2').html( $('input#foot2').sumConv('input#customers2') );
});
$('input#customers2').bind('keyup', function() {
$('#conversion2').html( $('input#foot2').sumConv('input#customers2') );
});
$('input#foot3').bind('keyup', function() {
$('#conversion3').html( $('input#foot3').sumConv('input#customers3') );
});
$('input#customers3').bind('keyup', function() {
$('#conversion3').html( $('input#foot3').sumConv('input#customers3') );
});
$('input#foot4').bind('keyup', function() {
$('#conversion4').html( $('input#foot4').sumConv('input#customers4') );
});
$('input#customers4').bind('keyup', function() {
$('#conversion4').html( $('input#foot4').sumConv('input#customers4') );
});
$('input#foot5').bind('keyup', function() {
$('#conversion5').html( $('input#foot5').sumConv('input#customers5') );
});
$('input#customers5').bind('keyup', function() {
$('#conversion5').html( $('input#foot5').sumConv('input#customers5') );
});
$('input#foot6').bind('keyup', function() {
$('#conversion6').html( $('input#foot6').sumConv('input#customers6') );
});
$('input#customers6').bind('keyup', function() {
$('#conversion6').html( $('input#foot6').sumConv('input#customers6') );
});
I suppose you have to apply parseFloat to your data. text method returns string, not number. Take a look at the simple example:
var avg1 = "1";
var avg2 = "1";
var avg3 = "1";
var avg4 = "1";
var avg5 = "1";
var avg6 = "1";
var sumavg = (avg1 + avg2 + avg3 + avg4 + avg5 + avg6) / 6;
sumavg will be 18518.5 and not 1.
Wrap all avg data with parseFloat:
var avgN = parseFloat($('#conversionN').text());
You're repeating a lot of code, so I advise employing a DRY technique to minimise that -- e.g. make a bindKeyUp function...
Anyway, you need numbers. .text() returns strings. E.g. "99" + "77" === "9977". This is where your crazy numbers might be coming from. Try this:
var avg1 = ~~$('#conversion1').text();
var avg2 = ~~$('#conversion2').text();
// repeat
~~ just converts its operand to a number (and floors it towards 0). More info.
Or, to make it clearer, use parseFloat:
var avg1 = parseFloat($('#conversion1').text());
var avg2 = parseFloat($('#conversion2').text());
// repeat

Categories