I'm looking for help in converting a particular elements in JSON message to an array using java script at run time. We wanted the script to be more generic. Actually we were trying the following which worked for single element and while changing it to handle for multiple elements at run time its not working.
//Working for Single element - Static
var bodyContext = JSON.parse(response.content)
if(bodyContext.companylist.company.constructor !== Array){
bodyContext.companylist.company = [bodyContext.companylist.company]
}
The above code works and converts Company in JSON message as a Array, Where as the below we tried for multiple elements is not working
//Not Working for multiple elements - dynamic
var bodyContext = JSON.parse(response.content)
var elementName = "";
//Loop runs every time and changes the value of elementName at every iteration
if(bodyContext.elementName .constructor !== Array){ //not working
bodyContext.elementName = [bodyContext.elementName] //Not working
}
instead of looking for "bodyContext.companylist.company" and converting into Array, "bodyContext.elementName" is checked and added to the bodycontext object.
how to handle this. ElementName variable along with JavaScript object is not recognized.
Please help.
you can JSON.parse(data) then you can fetch data from Javascript object like
$.each(Obj,function(key,value){
});
You'll want to use
bodyContext[elementName]
since
bodyContext.elementName
looks for a field in bodyContext named elementName, not the a field named after the value in elementName.
Also, you initialize elementName with "", and this won't match anything on the first iteration.
Related
I'm currently trying to populate a selection list from an external javascript array. It works but I'm trying to populate only certain values using an ID column, which is failing. I'm using check-boxes and an 'If' statement to see which box is checked, and populate the appropriate array values based on this selection. I'm then using another 'If' within a for loop to match the ID value in the array, and add the matching values to the selection. However, it seems that it is completely disregarding the condition and reading the entire array in to selection list. It could be an obvious mistake with my code as I am only a novice.
function populateIslandList () {
var form = document.forms["island_form"];
var islands = form.islands;
if (islands[0].checked){alert("works");
for (i = 0; i < pislands.length; i++)
if (pislands[i][1] = 1){
document.forms["location"].islands.options[i] =
new Option(pislands[i][0], i)}};
if (islands[1].checked){alert("works");
for (i = 0; i < pislands.length; i++)
if (pislands[i][1] = 2){
document.forms["location"].islands.options[i] =
new Option(pislands[i][0], i)}};
}
Your first mistake is here:
var islands = document.getElementById("island_form");
document.getElementById() returns a single DOM element, not a list of objects. So, thus islands[0] and islands[1] are going to be undefined and islands[0].checked will make a script error.
You can only have one DOM element with a given id. You can have multiple elements with a class name so maybe you should switch to using class names and be using document.getElementsByClassName("something")
FYI, you should be looking in the browser error console or debug console to see script errors as this should have given you an indication of some trouble here.
In an application I am working on I need to get a list of the names of all applicationScope variable then I need to cycle through them and filter out the ones starting with a know string say $xyx. I thought that the applicationScope.keySet().
I'm using this code for starter:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
if (itr.hasNext()){
var str:String = itr.next();
dBar.info(str,"Value = ");
}
if I put the variable col in a viewScope it shows a list of all the keys. but when I run the script the values displayed in the dBar info are not the keys but some other information that I'm not sure where it comes from.
I should just be able to iterat through the list of keys, am I missing something?
This code is in the before page loads event
After some poking around and experimenting I got this to work:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
while (itr.hasNext()){
var str:Map.Entry = itr.next();
if (str.substring(0,9) == "$wfsLock_"){
//do stuff
}
}
so I'm now a happy camper.
Although your code works in SSJS, it is not correct (and that's why I don't like SSJS...).
The applicationScope is an implementation of the java.util.Map interface and the keySet() method returns a Set containing the keys in that Map. Every entry is (probably) a String (other data types like integers are actually also valid). The line
var str:Map.Entry = itr.next();
doesn't cast it to a Map.Entry: it doesn't really do anything: str remains a string.
The Map interface also has an entrySet() method that returns the entries (Map.Entry). You can use that to retrieve the key as well as the value:
var it = applicationScope.entrySet().iterator();
while (it.hasNext()) {
var entry = it.next();
print( entry.getKey() + " = " + entry.getValue() );
}
(in this code the print() line will use the toString() method of the key as well as the value to send information to the console)
I see from your code that you've installed my XPages Debug Toolbar. You can also use that to quickly check what's in the scopes and what the actual datatype is.
I have an error in the following code and I can't find why...
Using UiApp I define a couple of ListBox like this in a for loop
var critGlist = app.createListBox().setName('critGlist'+n).setId('critGlist'+n).addChangeHandler(refreshGHandler).addChangeHandler(cHandlerG).setTag(listItem[n]);
I added a TAG to be able to retrieve a value in the handler function because when I add items to this list I do it like this :
for(var c=0;c<listItem[n].length;++c){
critGlist.addItem(listItem[n][c],c);// the returned value is c, the value shown is listItem[n][c]
}
Then in my handler function I retrieve the value c that is the index of an element of the array listItem[n]
Since I stored a stringified value of this array as a tag I have to retrieve the tag first and then using the index I get the desired value...
That's where it becomes problematic !
I tried the 3 following codes :
var idx = Number(e.parameter['critGlist'+c]);// this works and I get the index
var item = e.parameter.critGlist0_tag.split(',')[idx];// this also works for a fixed index (0 here) but I need to use it in a for loop so I tried the code below
var item = e.parameter['critGlist'+c]_tag.split(',')[idx];// this generates an syntax error
// error message :"Signe ; manquant avant l'instruction. (ligne 129, fichier "calculatrice Global")"
// which means : missing ; before statement (line 129...
Am I missing something obvious ? How should I write it differently ?
Obviously it is the underscore that is not accepted... but how could I not use it ?
Well, I have a few other possibilities to get the result I want (using a hidden widget for example or some other temporary storage of even let the listBox return the value instead of the index) but still I'd like to know why this syntax is wrong ...
I'm not asking for a different code (as mentioned before there are a lot of other ways to go) , just some explanation about what is wrong in this code and this #!##å»ÛÁØ underscore ;)
You will need to put the whole property within the brackets as below
var item = e.parameter['critGlist'+c+'_tag'].split(',')[idx];// this generates an syntax error
I've been having trouble setting a dynamic filter for oocharts.
I've looped through some things and have created an array (scenefilters) which I've joined to make a string. I've then tried to use this as a filter, which returns the error:
*JSONP.callbacks.request_63 && JSONP.callbacks.request_63({"error":"Invalid param {filters}: Filter string is not in valid format"});*
Now if I console.log the variable 'locationfilter2' and copy and paste it directly into the filter, it works fine - but it doesn't work just with the variable. Do I need to do something else to the variable to make sure it's a string?
var locationfilter = scenefilters.join(",");
var locationfilter2 = '"'+ locationfilter +'"';
var visits = new oo.Metric("54190402", "12m");
visits.setMetric("ga:visits");
visits.query.setFilter(locationfilter2);
visits.draw(timeline);
EDIT
I've tried outputting the variable to a textfield and copying it from there, same thing. The output is "ga:pagePath=~s101$,ga:pagePath=~s102$,ga:pagePath=~s103$,ga:pagePath=~s104$,ga:pagePath=~s105$,ga:pagePath=~s106$,ga:pagePath=~s107$,ga:pagePath=~s108$,ga:pagePath=~s109$,ga:pagePath=~s110$,ga:pagePath=~s111$,ga:pagePath=~s112$,ga:pagePath=~s113$,ga:pagePath=~s114$,ga:pagePath=~s115$,ga:pagePath=~s116$,ga:pagePath=~s117$,ga:pagePath=~s118$,ga:pagePath=~s119$,ga:pagePath=~s293$,ga:pagePath=~s301$"
And if I copy this directly into the filter, i.e. visits.query.setFilter("ga:pagePath=~s101$,ga:pagePath=~s102$,ga:pagePath=~s103$,ga:pagePath=~s104$,ga:pagePath=~s105$,ga:pagePath=~s106$,ga:pagePath=~s107$,ga:pagePath=~s108$,ga:pagePath=~s109$,ga:pagePath=~s110$,ga:pagePath=~s111$,ga:pagePath=~s112$,ga:pagePath=~s113$,ga:pagePath=~s114$,ga:pagePath=~s115$,ga:pagePath=~s116$,ga:pagePath=~s117$,ga:pagePath=~s118$,ga:pagePath=~s119$,ga:pagePath=~s293$,ga:pagePath=~s301$");
It works well. But if I use the variable I get the error. Anyone any ideas?
OK stupid one. Removed the ""s and it works fine.
A simple question I'm sure, but I can't figure it out.
I have some JSON returned from the server
while ($Row = mysql_fetch_array($params))
{
$jsondata[]= array('adc'=>$Row["adc"],
'adSNU'=>$Row["adSNU"],
'adname'=>$Row["adname"],
'adcl'=>$Row["adcl"],
'adt'=>$Row["adt"]);
};
echo json_encode(array("Ships" => $jsondata));
...which I use on the client side in an ajax call. It should be noted that the JSON is parsed into a globally declared object so to be available later, and that I've assumed that you know that I formated the ajax call properly...
if (ajaxRequest.readyState==4 && ajaxRequest.status==200 || ajaxRequest.status==0)
{
WShipsObject = JSON.parse(ajaxRequest.responseText);
var eeWShips = document.getElementById("eeWShipsContainer");
for (i=0;i<WShipsObject.Ships.length;i++)
{
newElement = WShipsObject.Ships;
newWShip = document.createElement("div");
newWShip.id = newElement[i].adSNU;
newWShip.class = newElement[i].adc;
eeWShips.appendChild(newWShip);
} // end for
}// If
You can see for example here that I've created HTML DIV elements inside a parent div with each new div having an id and a class. You will note also that I haven't used all the data returned in the object...
I use JQuery to handle the click on the object, and here is my problem, what I want to use is the id from the element to return another value, say for example adt value from the JSON at the same index. The trouble is that at the click event I no longer know the index because it is way after the element was created. ie I'm no longer in the forloop.
So how do I do this?
Here's what I tried, but I think I'm up the wrong tree... the .inArray() returns minus 1 in both test cases. Remember the object is globally available...
$(".wShip").click(function(){
var test1 = $.inArray(this.id, newElement.test);
var test2 = $.inArray(this.id, WShipsObject);
//alert(test1+"\n"+test2+"\n"+this.id);
});
For one you can simply use the ID attribute of the DIV to store a unique string, in your case it could be the index.
We do similar things in Google Closure / Javascript and if you wire up the event in the loop that you are creating the DIV in you can pass in a reference to the "current" object.
The later is the better / cleaner solution.
$(".wShip").click(function(){
var id = $(this).id;
var result;
WShipsObject.Ships.each(function(data) {
if(data.adSNU == id) {
result = data;
}
});
console.log(result);
}
I could not find a way of finding the index as asked, but I created a variation on the answer by Devraj.
In the solution I created a custom attribute called key into which I stored the index.
newWShip.key = i;
Later when I need the index back again I can use this.key inside the JQuery .click()method:
var key = this.key;
var adt = WShipsObject.Ships[key].adt;
You could argue that in fact I could store all the data into custom attributes, but I would argue that that would be unnecessary duplication of memory.