Adding up values to an associative array element - Javascript - javascript

I'm having some trouble adding values to existing values in arrays.
The code:
It all comes from a big string set as the value of an hidden element in the parent page.
var parent = $(window.opener.document).contents();
var data = parent.find("#hdn").val();
var sp1 = data.split("=x=");
$('#timerange').text(sp1[0]); // this is where I put the first part of the string
var sp2 = sp1[1].split("|"); // the remains of it will be used to fill arr1
var arr1 = {};
$.each(sp2, function(i, value){
if(value != ''){
var sp3 = value.split("<->");
arr1[sp3[0]] += parseFloat(sp3[2]); // this is where the problem goes. i can't sum the new value with the existing value of this element, it outputs "NaN" no matter what
$('#tableprnt tbody').append('<tr><td>'+sp3[0]+'</td><td>'+sp3[1]+'</td><td>'+sp3[2]+'</td><td>'+sp3[3]+'</td><td>'+sp3[4]+'</td><td>'+sp3[5]+'</td><td>'+sp3[6]+'</td><td>'+sp3[7]+'</td><td>'+sp3[8]+'</td><td>'+sp3[9]+'</td></tr>');
}
})
console.log(arr1);
The point of this is to append this informations to a table so I can print it.
data has the string that comes from the parent page which is something like this: 2017-12-28 - 2017-12-28=x=Company name<->big string here<->123.2<->2017-12-28<->2017-12-28<->2017-12-28<->another string here<->string<->string<->string|Company name<->big string here<->123.2<->2017-12-28<->2017-12-28<->2017-12-28<->another string here<->string<->string<->string| and it goes on.
Each element of arr1 (sp3[0] [string]) should have the sum of it's respective value (sp3[2] [float]), but all i can get is NaN for each one of these even though I'm using parseFloat().
Console displays *"{element 1: NaN, element 2: NaN}"*.
What am I missing?
Hope you can help me.

You are getting NaN because that's what should be returned as you are trying to increment the value for the key company_name
arr1[sp3[0]] += parseFloat(sp3[2]);
This would fail OR say will store NaN on the very first iteration in the value because the actual value against the key/property "Company Name" would be undefined and calling parseFloat() on undefined will return you NaN you need to check if the object has the property defined already then increment/add the value to existing value and if it is the first time then assign the value. change the above line to the following
arr1[sp3[0]] = (arr1.hasOwnProperty(sp3[0])) ? (arr1[sp3[0]] + parseFloat(sp3[2])) : (parseFloat(sp3[2]));

Related

Json array getting first data

I have an array which I declared as var myclinicsID = new Array(); and now, I push some data in it,when I alert it using alert(JSON.stringify(myclinicsID)) it gives me output of ["1","2","3","4"]
Now I want to use this for my function and when I look at in console, it gives me undefined, am I doing correct by my code :
getbarSeriesData(myclinicsID[0]['clinic_id'],data[i]['datemonths']);
I want to get myclinicsID first data element which is the value is 1
myclinicsID[0]['clinic_id']
Should be
myclinicsID[0]
All you need the array index. When you say myclinicsID[0]['clinic_id'], that is trying to get the clinic_id property of "1" which is obvious undefined.
Why myclinicsID[0]['clinic_id'] ? As there is nothing like clinic_id in your array.
Your array is single dimensional array. Hence, you can directly access the first element from an array using myclinicsID[0].
DEMO
var myclinicsID = new Array();
myclinicsID[0] = 1;
myclinicsID[1] = 2;
myclinicsID[2] = 3;
myclinicsID[3] = 4;
function getbarSeriesData(clientID) {
console.log(clientID);
alert(clientID);
}
getbarSeriesData(myclinicsID[0]);

adding input value in multidimensional array?

I am facing problem in java-script problem as
I have to collect all subrole from screen whenever user focus out from input field.this is my code
var subrole_id = [];
$("ul :input[class^='sub']").live('focusout', function() {
var get_id = $(this).attr('class').split("_");
var ids = get_id[2];
var ids_index = get_id[3];
subrole_id[ids][ids_index] = this.value;
});
but this is giving error
TypeError: subrole_id[ids] is undefined
subrole_id[ids][ids_index] = this.value;
Actually I want to collect value of subrole input field and add them in array with index ids one by one and before adding that value in array I have to check whether that present value is present in array or not if yes then do not add and give error.
Please suggest.
There isn't a true multidimensional array in javascript, just an array of array, so you have to create the subArray:
subrole_id[ids]=subrole_id[ids]||[];
subrole_id[ids][ids_index] = this.value;

jQuery getting value from dynamic array

I have an array with divs ids (in my case its all divs ID values od parent div (#area) ):
jQuery.fn.getIdArray = function () {
var ret = [];
$('[id]', this).each(function () {
ret.push(this.id);
});
return ret;
};
var array = $("#area").getIdArray();
I need to get an array field value, something like this:
var lef = $("#array".[0]).css("left");
Taking a wild swing at it (see my comment on the question):
var array = $("#area").getIdArray();
var lef=$("#" + array[0]).css("left");
That assumes that getIdArray returns an array of strings, where each string is an id value for a DOM element, and that you want to get the left value for the first of those elements.
So for instance, if the array comes back as:
["foo", "bar", "charlie"]
then the selector created by "#" + array[0] is #foo, so you end up getting the left value for the foo element.
If you have an actual JS array within your variable array just use bracket notation to access each individual ID.
// I have the # before-hand since I'm assuming you have just the ID name
var lef = $('#' + array[0]) // this will access the 1st one in the array
I think you are looking for this :
var divYouWantToChange = $("#"+array[0]);
I try to formulate this as an answer because getIdArray is not a jquery function and we don't know what it does. If you'd like to apply a custom filter to the $("#area") collection you can do so using filter. This will return a jquery object where you can get the .css("left") from.
If you'd like to save both the id's and the left property you can do so with the following code:
var objects=[];
$("#area").filter(function(){
$this=$(this);//cache the object
objects.push({id:$this.attr("id"),
left:$this.css("left")
};
});
console.log(objects);

Javascript Form: Only Changed Fields

I have a php-site with a form on which i output preselected values via php. On form submit I want to check which values have changed and just submit these via javascript.
These are the preselected values I passed over from php. It's important that I keep the associative array structure.
var pbData = jQuery.parseJSON("{
"GameMode":"DEATHMATCH",
"Current Map":"VEGAS JUNKYARD",
"Current Missions":["VEGAS JUNKYARD","VILLA","PRESIDIO","KILL HOUSE","MURDERTOWN","CQB TRAINING","STREETS","THREE KINGDOMS CASINO","IMPORT\/EXPORT;"],
"RoundDuration":"3 minutes"}");
I marked the error in the code.
<script>
function displayVars(){
var form = document.getElementById('settings');
var elems = form.elements;
var txt = "";
for (var index = 0; index < elems.length; index++){
var selIndex = elems[index].selectedIndex;
if (typeof selIndex !== "undefined"){
//the Index Name in the json-object and the name of the form-field are the same
var idxName = elems[index].name;
//HERE is the problem. I want to access the subobject via a variablename, so i can iterate through it, but that doesnt work.
console.log ("pbData default = "+pbData.idxName); //always undefined
if (elems[index].value !== pbData.idx_name){
//building a POST-Url
txt = txt + elems[index].name + "=" + elems[index].options[selIndex].value+"&";
}
}
}
console.log (txt);
return false;
}
</script>
I know that I could do this differently, also with jQuery. In my case as I have the preselected values as a php-variable in any case, i think it's easier like this.
I would really like to know how I can iterate through the subobjects via a variable that contains the object names.
This is due to how you'e trying to access the property of the (JSON) object. Consider
var o1 = {idxName: true},
o2 = {foo : 'bar'},
idxName = 'foo';
o1.idxName; // true
o2.idxName; // undefined
o2[idxName]; // 'bar'
You need to access the property via pbData[idxName].
Additionally, you're not escaping quotes in your JSON string, and line breaks need to be escaped as follows
var pbData = jQuery.parseJSON("{\
\"GameMode\":\"DEATHMATCH\",\
\"Current Map\":\"VEGAS JUNKYARD\",\
\"Current Missions\":[\"VEGAS JUNKYARD\",\"VILLA\",\"PRESIDIO\",\"KILL HOUSE\",\"MURDERTOWN\",\"CQB TRAINING\",\"STREETS\",\"THREE KINGDOMS CASINO\",\"IMPORT\/EXPORT;\"],\
\"RoundDuration\":\"3 minutes\"}");
In Javascript you could keep an object or array with initial values and only post those values that are changed.
But in fact, I would do something similar, but in PHP. You can keep the original values in the session and compare the posted values to those initial values to see what has changed. That way, you won't depend on Javascript. Not only may Javascript be disabled, but also, a fast user may theoretically post the form before the Javascript has run. To move this check to PHP eliminates that risk.

Get inputs value and separated by "|"

I have inputs and I need to get values and separated by "|" symbol.
My input:
Output what I need:
00:00|00:00|00:00
My code is :
(and it's not working)
var timesArray = $('table').find('input');
var times = timesArray.val();
$('.alltimes').val(times);
Given that .val returns the value of each element (whatever input type it is in your screenshot), then you can use .map: http://jsfiddle.net/RrCYD/.
var values = $("input").map(function() {
return $(this).val(); // map each element to its value
}).get().join("|"); // get real array and join
See comments in code:
// Create an array to store the input values
var inputValues = [];
// Iterate over input's and store their value in the array
$('table').find('input').each(function () {
inputValues.push(this.value);
});
// Create pipe=delimited string from array of values
var delimitedInputValues = inputValues.join("|");
Additional Information
MDN - array.join
jQuery - .each()

Categories

Resources