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
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'm trying to add inputs iteratively, and be able to run a calculation independently on each, but can not seem to apply the closure principles. The calculation function is only working on the last item added. I've tried using a for loop within as well as around the main function (addIt()) but it only seems to make things worse...
Here's the basic html:
<button class="btn btn-default btn-block" onClick="addIt('Item'+count)">Add One</button>
<form>
<div id="itemForm"></div>
<form>
And here is my overly complex and inelegant js (by the way, I'm open to better ways of doing this, so please don't hesitate to jump all over this):
count = 0;
addIt = function(p) {
count++;
var itFrm = document.getElementById("itemForm");
var itDiv = document.createElement("div");
var children = itFrm.children.length + 1
itDiv.setAttribute("id", "itemDiv")
itDiv.appendChild(document.createTextNode(p));
itFrm.appendChild(itDiv);
var remove = document.createElement("a");
var linkText = document.createTextNode("Remove It");
remove.setAttribute("href", "#");
remove.setAttribute("onClick", "removeIt()");
remove.appendChild(linkText);
var brk = document.createElement("br");
var num = document.createElement("input");
num.setAttribute("id", "numInput"+count);
num.setAttribute("type", "number");
num.oninput = function () {
var numInput = document.getElementById('numInput'+count).value ;
var divisor = 10;
var result = document.getElementById('result'+count);
var myResult = (Number(numInput) / Number(divisor));
result.value = myResult;
};
num.setAttribute("placeholder", "Set number...");
var clc = document.createElement("input");
clc.setAttribute("id", "result"+count);
clc.setAttribute("readonly", "readonly");
clc.setAttribute("placeholder", "After Calculation...");
var hr = document.createElement("hr");
itDiv.appendChild(remove);
itDiv.appendChild(num);
itDiv.insertBefore(brk, num);
itDiv.appendChild(clc);
itDiv.appendChild(hr);
};
function removeIt(elem) {
var elem = document.getElementById('itemDiv');
elem.parentNode.removeChild(elem);
return false;
};
I tried to setup a jsfiddle here but for some reason the removeIt function doesn't work there, although it's working locally for me, but only removes the oldest iteration. Any thoughts on how I've botched that are welcomed and appreciated as well.
var countString = count.toString();
num.oninput = function() {
var numInput = document.getElementById('numInput' + countString).value;
var divisor = 10;
var result = document.getElementById('result' + countString);
var myResult = (Number(numInput) / Number(divisor));
result.value = myResult; };
It was a scoping issue with count. Its basically a global variable so the closure will look for it. Use a local variable that gets re declared on each button press to fix it.
Problem is simple. When the scoring variable is higher than 10, I can't make the sprawdzRyzyko() function return boolean true.
var high_ryzyko_kraj = ['Polska', 'Afganistan', 'Ukraina'];
var less_ryzyko_kraj = ['Serbia', 'Egipt'];
var scoring = 0;
$('#country, #country-bd, #country-wd').change(function(){
caunt = $(this).val();
var arr = $.inArray(caunt, high_ryzyko_kraj);
var drr = $.inArray(caunt, less_ryzyko_kraj);
if (arr>-1){
scoring += 4 ;
sprawdzRyzyko();
}else if(drr>-1){
scoring += 2 ;
sprawdzRyzyko();
}
});
console.log(scoring);
var sprawdzRyzyko = function () {
if (scoring > 10){
return true;
}
}
// For Testing
var a = sprawdzRyzyko();
if (a){
console.log("Hey it works!");
}
Fiddle
You can set the scoring variable above 10 by sting the selects to 3 countries in high_ryzyko_kraj array.
Here is a solution. Answer Fiddle
function sprawdzRyzyko() {
if (scoring > 10) {
return true;
}
};
Try this: http://jsfiddle.net/uJA39/15/
var high_ryzyko_kraj = ['Polska', 'Afganistan', 'Ukraina'];
var less_ryzyko_kraj = ['Serbia', 'Egipt'];
var scoring = 0;
var sprawdzRyzyko = false;
$('#country, #country-bd, #country-wd').change(function(){
if ($.inArray($(this).val(), high_ryzyko_kraj)>-1)
scoring += 4;
else if($.inArray($(this).val(), less_ryzyko_kraj)>-1)
scoring += 2;
if (scoring > 10){
alert("Hey it works!");
sprawdzRyzyko=true;
}
});
I don't know your dynamics but are you sure that scoring shouldn't be set to 0 (zero) every time DDL changes (so inside change event handler)?
Hope this helps,
Have a nice day,
Alberto
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();
});
I am trying to calculate all fields in the form which have the same class (shown below in the code), I have managed to get this to work, I think I may be setting the wrong value types in javascript as its not adding them together correctly. Its adding them on top of each other and not to each other. so instead of 4.00 + 5.50 equalling to 9.50 it would read 04.0005.50.
function calculate() {
var total = 0;
$('input.calc').each(function() {
var num = this.value;
//Number(this.value, 10);
if (!isNaN(num)) {
total += num.toFixed(2);
}
});
$("#total").val(total);
}
Any help its appreciated, Thanks
<script language="javascript">
function calculate() {
var total = 0;
$('input.calc').each(function() {
var num = this.value;
//Number(this.value, 10);
if (!isNaN(num)) {
total += num.parseFloat(num);
}
});
$("#total").val(total);
}
</script>
function calculate() {
var total = 0;
$('input.calc').each(function() {
var num = parseFloat(this.value);
//Number(this.value, 10);
if (!isNaN(num)) {
total += num;
}
});
$("#total").val(total);
}