function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SaintMichaelSaintMichael 

passing Apex List<String> to javascript array object

In my visualforce page, I have an array:

var availableTags = [
			"ActionScript",
			"AppleScript",
			"Asp",
			"BASIC",
			"C",
			"C++",
			"Clojure",
			"COBOL",
			"ColdFusion",
			"Erlang",
			"Fortran",
			"Groovy",
			"Haskell",
			"Java",
			"JavaScript",
			"Lisp",
			"Perl",
			"PHP",
			"Python",
			"Ruby",
			"Scala",
			"Scheme"
		];
		

 How can I populate this array with data from salesforce?

 

 

I read on the boards that this would work:

availableTags = "{!designations}";

 But it doesnt work. My data is not getting into the javascript array.

I tried this with the repeat tag as mentioned Here

but still no good.

 

Shouldn't this be simple?

 

 

Best Answer chosen by Admin (Salesforce Developers) 
vishal@forcevishal@force

Yes, it works that way.

 

A simple example :

 

Visualforce :

 

<apex:page controller="javascriptLearning">
<script>
    alert('{!lstAssignToArray}');
    var myList = new Array();
    myList = '{!lstAssignToArray}';
    alert(myList);
</script>
</apex:page>

 

Apex Controller:

 

public with sharing class javascriptLearning {
    public List<String> lstAssignToArray    {get;set;}
    
    public javascriptLearning()
    {
        lstAssignToArray = new List<String>();
        lstAssignToArray.add('ABC');
        lstAssignToArray.add('DEF');
        lstAssignToArray.add('GHI');
        lstAssignToArray.add('JKL');
        lstAssignToArray.add('MNO');
        lstAssignToArray.add('PQR');
        lstAssignToArray.add('STU');
        lstAssignToArray.add('VWX');
        lstAssignToArray.add('YZ');
    }
}

 

This works for me and in my alerts, I see that array has those values from the list!

All Answers

vishal@forcevishal@force

Yes, it works that way.

 

A simple example :

 

Visualforce :

 

<apex:page controller="javascriptLearning">
<script>
    alert('{!lstAssignToArray}');
    var myList = new Array();
    myList = '{!lstAssignToArray}';
    alert(myList);
</script>
</apex:page>

 

Apex Controller:

 

public with sharing class javascriptLearning {
    public List<String> lstAssignToArray    {get;set;}
    
    public javascriptLearning()
    {
        lstAssignToArray = new List<String>();
        lstAssignToArray.add('ABC');
        lstAssignToArray.add('DEF');
        lstAssignToArray.add('GHI');
        lstAssignToArray.add('JKL');
        lstAssignToArray.add('MNO');
        lstAssignToArray.add('PQR');
        lstAssignToArray.add('STU');
        lstAssignToArray.add('VWX');
        lstAssignToArray.add('YZ');
    }
}

 

This works for me and in my alerts, I see that array has those values from the list!

This was selected as the best answer
SFDC_VikashSFDC_Vikash

It is working fine for me 

 

availableTags = '{!designations}';

 

May be it is not working due to some other javascript error, please make sure there is not other error in code.

SaintMichaelSaintMichael

Ok, it's getting into the array, but not the JSON format I need.

 

Hopefully, Remote JavaScripting can solve this for me.

 

So far I'm getting : controller not found when using Remote JavaScripting. Maybe it's not active yet.

I'll contact salesforce.

SaintMichaelSaintMichael

I ened up doing this to get the javascript array that I want:

 

for(Designation_Abbreviation__c d: abbs){
		designations.add(String.escapeSingleQuotes(d.Name +' '+d.Designation__r.Name));
	}
	
	JSONString = JSON.serialize(designations);

 I escape then serialze.

SaintMichaelSaintMichael

Addition:

 

I had to remove the single quotes in the visualforce page:

 

from this:

var availableTags = new Array();
availableTags = '{!JSONString}';

 to this:

var availableTags = new Array();
availableTags = {!JSONString};

 

Removing the single quotes around the assignment value along with this:

JSONString = JSON.serialize(designations);

 When I tried using String.escapeSingleQuotes, that caused a problem.

So, no need to use String.escapeSingleQuotes.

RamsRams
Hi,

I need the same thing in reverse. Can you help me out. When i am clicking button from visualforce page. Some list of values i am getting. I need those values in to apex class. How can i get that list of string values in to apex class when button click happen. Thanks in advance.

Thanks,
Rams.
uHaveOptionsuHaveOptions
I am able to pass my array into javascript using this method, but it enters the entire array as one item in place [0], rather than breaking it up into multiple items. Any suggestions?
I am trying to iterate over the items  using this code:

var locs=[];
locs='{!getlocList}';
      console.log(locs.length);
      for(var i=0; i < locs.length; ++i){
console.log('location:'+locs[i]);
    }


This is my apex:

public class ControllerJSGeo{
    public List<String> getlocList{get;set;}
public ControllerJSGeo(ApexPages.StandardController stdController){
        pId = ApexPages.CurrentPage().getParameters().get('id');
    getlocList();
    }

public void getlocList(){
List<String> getList=new List<String>();
List<Property__c> rawPS=[select name,property_address__c from property__c limit 5];
        for(Property__c rawP : rawPS){
        getList.add(rawP.property_address__c);
        }
getlocList=getList;
}

}

 
Ray Kao 8Ray Kao 8
Just rewrite the code and examine the result...

<!-- Visualforce Page -->
  <script>
    var myList = new Array();
    myList = '{!lstAssignToArray}';
    alert(myList.length);
    alert(myList[0]);
  </script>

The actual result is
myList.length  ==> 44
myList[0] ==> '['

It expects to be 9, 'ABC'

So, vishal@force's answer is wrong!!

It does not work at all!!

It should not be marked as an answer!!
 
narsavagepnarsavagep

The array is put into the javascript text as comma-separated text... surrounded by brackets.  "[a, b, c]"

So you need to split it to use it as an array.  Also note that you should trim the excess spaces off the values before you use them.

Example:

var csvList = '{!lstAssignToArray}';
csvList = csvList.replace('[','').replace(']','');
var arrList = csvList.split(',');
var arrListLen = arrList.length;
for (var i = 0; i < arrListLen; i++) {
	alert( arrList[i].trim() );
}


I never tested or developed how to handle commas within the array... not sure how it would work.  My need was a set list of values so I was sure to never have commas.

Snehal HarsheSnehal Harshe
Hello
I am new to Data Science
Due to the growing demand for expertise in data sciences, job opportunities across various industries are increasing significantly worldwide. Go for Data Science Course in Pune (https://61e68ebb3e110.site123.me/) to perform efficient analysis using modern data analysis software and Get an industry-recognized Data Scientist Certificate. In short, understanding Python is one of the valuable skills needed for a data science career. Though it hasn't always been, Python is the programming language of choice for data science. In 2018, 66% of data scientists reported using Python daily, making it the number one language for analytics professionals.