Im trying to do a sum of values i get from id but it keeps appending second value to first instead of doing sum as it should.
Example 23+25=2325
Heres my code:
This is the code im using to sum.
$('input').blur(function() {
for (var i=1; i<=value; i++) {
var one = document.getElementById("veb_blocos-"+i).value;
var two = document.getElementById("veb_pellet-"+i).value;
var sum1 = one+two;
document.getElementById("total1-"+i).value = sum1;
};
});
Try this:
var one = parseInt(document.getElementById("veb_blocos-"+i).value, 10);
var two = parseInt(document.getElementById("veb_pellet-"+i).value, 10);
Because the value of an input is a string. Cast it to int.
$('input').blur(function() {
for (var i=1; i<=value; i++) {
var one = document.getElementById("veb_blocos-"+i).value;
var two = document.getElementById("veb_pellet-"+i).value;
var sum1 = parseInt(one,10)+parseInt(two,10);
document.getElementById("total1-"+i).value = sum1;
};
});
Here is the safest possible solution (presuming the requested DOM nodes are present):
$('input').blur(function () {
var i = 0,
one = 0,
two = 0;
for (i = 1; i <= value; i += 1) {
one = Number(document.getElementById("veb_blocos-" + i).value);
two = Number(document.getElementById("veb_pellet-" + i).value);
if (isNaN(one)) {
one = 0;
}
if (isNaN(two)) {
two = 0;
}
document.getElementById("total1-" + i).value = one + two;
};
});
Try:
$('input').blur(function() {
for (var i=1; i<=value; i++) {
var one = parseInt(document.getElementById("veb_blocos-"+i).value);
var two = parseInt(document.getElementById("veb_pellet-"+i).value);
var sum1 = one+two;
document.getElementById("total1-"+i).value = sum1;
};
});
It's because your values are string datatypes instead of a number type. You'll need to parse them first.
$('input').blur(function() {
for (var i=1; i<=value; i++) {
var one = parseFloat(document.getElementById("veb_blocos-"+i).value);
var two = parseFloat(document.getElementById("veb_pellet-"+i).value);
var sum1 = one+two;
document.getElementById("total1-"+i).value = sum1;
};
});
Related
so I've been stuck at this problem for a few days:
My Input is this:
"255,255,255,10,251,91,31,4,220,220,220,1"
Its a String with 3 different RGB values, which also come with a number which indicates their quantity going from hightest to lowest.
You could translate the String from above to:
"RED1, GREEN1, BLUE1, QUANTITY1, RED2, GREEN2 ... "
While the 1 stands for the first color and 2 for the second and so on.
What I need to return is the first color without its quantity.
So my output should look like this:
"255,255,255,251,91,31,220,220,220"
I've tried various of things, one is this function:
var firstC, secondC, thirdC;
var pointer = "firstC";
function getEachColorValue(color) {
var startIndex = 0;
var endIndex = 0;
for (var i = 0; i < color.length; i++) {
if (color.charAt(i) == ",") {
endIndex = i;
if (pointer == "firstC") {
firstC = color.substring(startIndex, endIndex);
startIndex = endIndex + 1;
pointer = "secondC";
} else if (pointer == "secondC") {
secondC = color.substring(startIndex, endIndex);
startIndex = endIndex + 1;
pointer = "thirdC";
} else if (pointer == "thirdC") {
thirdC = color.substring(startIndex, endIndex);
startIndex = endIndex;
pointer = "firstC";
}
}
}
}
This pushes RED1 in firstC, GREEN1 in secondC and BLUE1 in thirdC
I thought about doing that one time, use a function to write firstC, secondC, thirdC into an array, reset them. Then cut col3 into a substring without the first color pallet, then repeat.
// Global variables
var stringHolder;
var newString;
var counter = 0;
var colorSetHT = new Array;
// main
createSubstring(col3);
function createSubstring(color) {
var startIndex = 0;
var endIndex = 0;
for (var i = 0; i < color.length; i++) {
if (color.charAt(i) == ",") {
counter++;
endIndex = i;
}
if (counter == 4) {
stringHolder = color.substring(startIndex, endIndex);
alert(stringHolder);
newString = color.substring(endIndex+1, color.length);
getEachColorValue(stringHolder);
colorSetHT.push(firstC, secondC, thirdC)
colorReset();
counter = 0;
stringHolder = "";
// createSubstring(newString); // ?
}
}
}
I've tried this, but had no luck so far. I even tried to do it recursively.
Im kinda new to Javascript (actually doing it for Extendscript), I think theres a way easier way, working with split/slice but I havent been able to find one yet. I tried to make it as easy and fast to read as possible, please let me know if I can provide any further information, thanks in advance!
Here is how to do it with split.
var input = "255,255,255,10,251,91,31,4,220,220,220,1";
var inputArray = input.split(",");
var outputArray = [];
for(let i = 0;i<inputArray.length;i++)
{
if(i%4 != 3)
{
outputArray.push(inputArray[i]);
}
}
var output = outputArray.join(",");
console.log(output);
Try
let output = input.split(',').filter((x,i)=> i%4-3).join();
let input="255,255,255,10,251,91,31,4,220,220,220,1"
let output = input.split(',').filter((x,i)=> i%4-3).join();
console.log(output);
Use a simple for loop like so:
const str = "255,255,255,10,251,91,31,4,220,220,220,1";
var colors = str.split(",");
var x = Math.floor(colours.length / 4);
while (x--) {
colors.splice((x + 1) * 4 - 1, 1);
}
colors = colors.join(",");
console.log(colors);
I have following code:
$scope.showTotal = function() {
$scope.pT = [];
var iT = 0;
for (var i = 0; i < $scope.od.length; i++) {
console.log($scope.od[i]['bpr']);
iT += $scope.od[i]['bpr'];
// also tried this -> iT = iT + $scope.od[i]['bpr']
}
$scope.pT.push({iTotal: iT});
console.log($scope.popupTotals);
$scope.showPopupNow = true;
}
But I don't know why it's not working.
If the bpr is for example 50 and 43.1034, then it logs the output in console something like this, iTotal:"050.000043.1034"
I am new to JavaScript and I started it directly with AngularJS.
So please help me with arithmetic operators in JS.
Thank You.
$scope.showTotal = function() {
$scope.popupTotals = [];
var itemtotal = 0;
for (var i = 0; i < $scope.order.length; i++) {
console.log($scope.order[i]['baseprice']);
itemtotal += parseFloat($scope.order[i]['baseprice']);
// parseFloat will convert string to number and add the number instead of concatenating the strings
}
$scope.popupTotals.push({itembasetotal : itemtotal});
console.log($scope.popupTotals);
$scope.showPopupNow = true;
}
You are incrementing i inside the loop .Remove the duplicate i and I suspect that your $scope.order[i]['baseprice'] is not an integer. So convert it to an integer using parseFloat
$scope.showTotal = function(){
$scope.popupTotals = [];
var itemtotal = 0;
for (var i = 0; i<$scope.order.length; i++){
console.log($scope.order[i]['baseprice']);
itemtotal += parseFloat($scope.order[i]['baseprice']);
//also tried this -> itemtotal = itemtotal + $scope.order[i]['baseprice']
//i++; No need to increment here
}
$scope.popupTotals.push({itembasetotal : itemtotal});
console.log($scope.popupTotals);
$scope.showPopupNow = true;
}
I'm trying to get the following code to add each number in the element separately and not the whole array together but the dash seems to stop the loop from calculating the total sum of each element. I can't seem to make it so it'll except any length of number for the variable. Any help is greatly appreciated!
var creditNum = [];
creditNum[0] = ('4916-2600-1804-0530');
creditNum[1] = ('4779-252888-3972');
creditNum[2] = ('4252-278893-7978');
creditNum[3] = ('4556-4242-9283-2260');
var allNum = [];
var total = 0;
var num = 0;
var cnt = 0;
for (var i = 0; i < creditNum.length; i++) {
num = creditNum[i];
for (var j = 1; j <= num.length; j++) {
var num = creditNum[i].substring(cnt, j);
console.log(creditNum[i].charAt(cnt));
console.log(cnt, j);
cnt = cnt + 1;
}
if (num != "-") j = j++;
console.log(parseInt(num));
}
console.log(total);
Assuming the intent is to add '4916-2600-1804-0530' and output the value as 49, then the following modification will achieve that.
var creditNum = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
for (var i = 0; i < creditNum.length; i++) {
var num = creditNum[i].replace(/\-/g, '');
var total = 0;
for (var j = 0; j < num.length; j++) {
total += Number(num[j]);
}
console.log(creditNum[i], total);
}
Using native array methods, the code can be refactored as the following.
var creditNumbers = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
creditNumbers.forEach(function(creditNumber) {
var num = creditNumber.replace(/\-/g, '').split('');
var total = num.reduce(function(tally, val) {
return tally += Number(val);
}, 0);
console.log(creditNumber, total);
});
I have a json response where have to calculate the average of "throughput_kbps" where protocol name is "TCP" for each result array.
I using Javascript/Angularjs for this
Please refer This json
Thanx in advance
You could do something like this:
var len1 = obj['flows'].length;
for (var i=0; i<len1; i++)
{
var tmp = obj.['flows'][i];
var len2 = tmp.['results'].length;
var mean = 0;
for (var j=0; j<len2; ++j)
{
var tmpResult = tmp.['results'][j];
if (tmpResult['protocol'] === 'TCP')
mean += tmpResult['throughput_kbps'];
}
console.log(mean);
}
Try this
var sum = 0;
var count = 0;
data.flows.map(function(d){
return d.results.filter(function(res){
if(res.protocol == 'TCP'){
sum += res.throughput_kbps;
count++;
return sum;
}
})
});
var avg = sum/count;
Pass your JSON as an argument to this function. This'll return you the average throughput you ask for.
function calculateThroughput(json){
var flowsObj = json.flows;
var throughputSum = 0;
var noOfSamples = 0;
for(noOfFlows in flowsObj){
var resultObj = flowsObj[noOfFlows].results;
for(noOfResults in resultObj){
if(resultObj[noOfResults].protocol == "TCP"){
throughputSum += resultObj[noOfResults].throughput_kbps;
noOfSamples++;
}
}
}
return (throughputSum/noOfSamples);
};
Hope this helps.
I have array like this:
var notes = ["user1,date:13/2/2008,note:blablabla", "user1,date:15/2/2008,note:blablabla", "user1,date:17/2/2008,note:blablabla", "user1,date:13/3/2008,note:blablabla"];
And I have
var search_date="17/2/2008";
I want to find last occurence of note and user for that note. Anyone knows how? Thanks in advance for your reply.
Try this:
var highestIndex = 0;
for (var i = 0; i < notes.length; i++){
if (notes[i].indexOf(search_date) != -1){
highestIndex = i;
}
}
//after for loop, highestIndex contains the last index containing the search date.
Then to get the user, you can parse like this:
var user = notes[highestIndex].substring(0, notes[highestIndex].indexOf(',') - 1);
You can iterate the array and check the attribute
or
you can user underscore.js: http://underscorejs.org/#filter
for (var i = 0; i < notes; i++) {
if (notes[i].indexOf(search_date) != -1) {
// notes [i] contain your date
}
}
var match = JSON.stringify(notes).match("\"([^,]*),date\:"+search_date+",note\:([^,]*)\"");
alert(match[1]);
alert(match[2]);
works ;-)
Something like this:
var notes = ["user1,date:13/2/2008,note:blablabla", "user1,date:15/2/2008,note:blablabla", "user1,date:17/2/2008,note:blablabla", "user1,date:13/3/2008,note:blablabla"];
var search_date="17/2/2008";
var res = [];
for(var i = 0; i < notes.length; i++) {
var note = notes[i];
if(note.indexOf(search_date) !== -1) {
res.push(note.substring(note.indexOf('note:') + 1), note.length);
}
}
var noteYouWanted = res[res.length - 1];
For the last occurrence and if performance matters:
var notes = ['user1,date:13/2/2008,note:blablabla', 'user1,date:15/2/2008,note:blablabla', 'user1,date:17/2/2008,note:blablabla', 'user1,date:13/3/2008,note:blablabla'],
search = '17/2/2008',
notesLength = notes.length - 1,
counter,
highestIndex = null;
for (counter = notesLength; counter >= 0; counter--) {
if (notes[counter].indexOf(search) !== -1) {
highestIndex = counter;
break;
}
}
// do something with notes[highestIndex]
var notes = ["user1,date:13/2/2008,note:blablabla", "user1,date:15/2/2008,note:blablabla", "user1,date:17/2/2008,note:blablabla", "user1,date:13/3/2008,note:blablabla"];
var search_date="17/2/2008";
var user, note;
$.each(notes, function(i) {
var search = new RegExp('\\b' + search_date + '\\b','i');
// if search term is found
if (notes[i].match(search)) {
var arr = notes[i].split(',');
user = arr[0];
note = arr[2].substr(5);
}
}); // end loop
console.log(user);
console.log(note);
example here: http://jsfiddle.net/Misiu/Wn7Rw/