This is related to Lightning component framework. Though, I have passed challenge (till 4), however result is not as expected. I am passing boatTypeId as a parameter from helper-onSearch to apex method-getBoats(). getBoats() return list of boats having the same boatTypeId. Below is my helper and the apex class.  ({     onSearch : function(component, event, helper) {        // console.log('In Helper');         var action=component.get('c.getBoats');         var btypeId =component.get("v.boatTypeId");         console.log('BoatSearchResult helper boattypeId '+btypeId);         action.setParam({"boatTypeId" :btypeId});         action.setCallback(this,function(response) {             if(response.getState() === 'SUCCESS')             {                 console.log('response from server'+ response.getReturnValue());                 var boatslist = response.getReturnValue();                 console.log('Number of Boats returned'+boatslist.length);                 component.set("v.boats",boatslist);             }              else             {                 console.log('Error caught in !!!');             }         });         $A.enqueueAction(action);     } })     public with sharing class BoatSearchResults {      @Auraenabled     public static List&lt;Boat__c&gt; getBoats(string boatTypeId)     {        if(boatTypeId != '')        {            system.debug(boatTypeId);            system.debug('Hello again');            return ([Select Id, BoatType__c , Contact__r.Name, Name, picture__c from Boat__c Where BoatType__c = :boatTypeId]);            // return ([SELECT Id, BoatType__c, picture__c, Name,contact__r.Name from Boat__c]);             }        else        {            system.debug('Hello again2');            return ([SELECT Id, BoatType__c, picture__c, Name,contact__r.Name from Boat__c]);         }     } }   Couple of issues here, I find here:   boatTypeId passed in the getBoats() is always null  If boatTypeId is null , then else part of getBoats() should be executed, but  if part of the method is executed all the times. (Maybe I am missing basics  of SOQL here)   Can someone point me in the right direction?
121649
I am unable to pass parameter from the lightning controller to the apex class. Whenever I use debug the passed value seems null.  JavaScript Controller  add : function(cmp,event,helper) {      event.target.parentNode.style.display = 'none';     document.getElementById("cartdiv").style.display = 'block';     var selectedAccount =event.target.id;      var act = cmp.get("c.Cartveg");     act.setParams({"s":selectedAccount});     act.setParams({"cartlist" : cmp.get("v.cart")});     act.setCallback(this,function(a){         cmp.set("v.cartitem",a.getReturnValue());     });            $A.enqueueAction(act);     cmp.set("v.whichButton", selectedAccount); }   Apex Class  @AuraEnabled public static List&lt;Vegetable__c&gt; Cartveg(string s,List&lt;Vegetable__c&gt; cartlist) {       system.debug(s);   List&lt;Vegetable__c&gt;  clist= [SELECT Id, Name , Price__c , img__c                                  FROM Vegetable__c where Name =:s];      clist.addAll(cartlist);      system.debug(clist);     return clist; }   Value of s is null. Please help
122134
I am dynamically creating a toast as shown below. This toast is created when response is received from server. I have created a component for toast and am dynamically creating it using $A.createComponent. The toast is getting fired when I am testing it in SF1 simulator or when I  have added my component in app builder. However, it is not getting thrown on screen, thought it is generated as seen in console.log, in case when I test it using standalone app (adding parent component to .app file and then preview) OR when i render my component using ltng:out in a VF page. What may be the reason for this?     controller from where dynamically toast is created:   . . . if (component.isValid() &amp;&amp; state === "SUCCESS") {             console.log("Values updated successfully!");             //$A.get('e.force:refreshView').fire(); //this is also not working             this.createToastComponent(component, 'success', 'Success!', 'Record Saved successfully!');      createToastComponent : function(component, type, title, message){      $A.createComponent(         "c:ToastComponent",         {             "type" : type,             "title" : title,             "message": message         },         function(newToast, status, errorMessage){             if(errorMessage === null){                 //do nothing             }             else{                 console.log('Toast errorMessage: '+ errorMessage);             }         }     ); },      toastComponent UPDATED:   &lt;aura:component &gt; &lt;aura:attribute name="type" type="String" /&gt; &lt;aura:attribute name="title" type="String" /&gt; &lt;aura:attribute name="message" type="String" /&gt; &lt;!--&lt;aura:handler name="init" action="{!c.handleInit}" value="{!this}" /&gt;--&gt;  &lt;div class="slds"&gt;     &lt;div class="slds-notify_container"&gt;         &lt;div aura:id="successToast" class="slds-notify slds-notify--toast slds-theme--success" role="alert"&gt;             &lt;span class="slds-assistive-text"&gt;Success&lt;/span&gt;             &lt;button class="slds-button slds-notify__close slds-button--icon-inverse" title="Close"&gt;                 &lt;c:SVGIcon svgPath="/resource/SLDS214/assets/icons/action-sprite/svg/symbols.svg#close"                            class="slds-button__icon slds-button__icon--large" assistiveText="Close"/&gt;                 &lt;span class="slds-assistive-text"&gt;Close&lt;/span&gt;             &lt;/button&gt;             &lt;div class="slds-notify__content slds-grid"&gt;                 &lt;div class="slds-col slds-align-middle"&gt;                     &lt;h2 class="slds-text-heading--small "&gt;{!v.message}&lt;/h2&gt;                 &lt;/div&gt;             &lt;/div&gt;         &lt;/div&gt;     &lt;/div&gt; &lt;/div&gt;        toast component controller:   ({ handleInit : function(component, event, helper) {      var toastEvent = $A.get("e.force:showToast");     console.log('toastEvent: '+ toastEvent+ 'title: '+ component.get("v.title")+ 'message: '+ component.get("v.message"));     toastEvent.setParams({         "title": component.get("v.title"),         "message":  component.get("v.message"),         "type": component.get("v.type")     });     toastEvent.fire(); }   })     Output in console.log:   toastEvent: SecureAuraEvent: [object Object]{ key: {"namespace":"c"} }title: SUCCESS!message: Record created Successfully
56738
In Field Service Lightning I have a Trigger on ServiceReport which sends an email with attachment coming from ContentVersion.   This is the Test class I have written.  @isTest  private class testCreateServiceReport{       static testMethod void validateWO() {       WorkOrder wo = new WorkOrder();       wo.subject = 'Testing';       insert wo;       ServiceAppointment sa = new ServiceAppointment();       sa.ParentRecordId = wo.Id;       sa.EarliestStartTime = DateTime.now();       sa.DueDate = DateTime.now();       insert sa;       List&lt;ServiceReportLayout&gt; srl = [Select Id FROM ServiceReportLayout];       ServiceReport sr = new ServiceReport();       sr.ParentId = sa.Id;       sr.Template = srl[0].Id; //Need to check if there is a way to avoid srl[0] notation       insert sr; //If I comment this the text result is pass. When I enable it I get too see the below mentioned error.  }  }   This is the error Methods defined as TestMethod do not support Web service callouts I know that we need to write Test Classes for code that involves web service callouts using setMock() but I dont understand in what way inserting ServiceReport is related to making a callout.  Any help on this will be really helpful.
63671
Below is my code to create the component dynamically - The component is "ui:inputselect"  $A.createComponent(             RecoveryLineItem.Attributes[i].name,{                 "class" : "slds-input ",                 "aura:id" : 'ExampleId',                 "label" : RecoveryLineItem.Attributes[i].label,                 "multiple" : RecoveryLineItem.Attributes[i].multiple             }, ....   ..  console.log(component.find('ExampleId').get("v.value"))    Or console.log(component.find('ExampleId'))  is Giving as 'Undefined"  How to access the aura:id of the dynamically created components?
18923
I am trying to write a test for a trigger that is firing a future apex callout :  The trigger calls the callBillingService method from this class:  public class BillingCalloutService {     //Implement business and callout logic methods here     @Future(callout=true)     public static void callBillingService(List&lt;Id&gt; recordIds) {         List&lt;Project__c&gt; projects = [Select Id, ProjectRef__c,Billable_Amount__c from Project__c Where Id = :recordIds];          List&lt;Project__c&gt; projectsToUpdate = new List&lt;Project__c&gt;();          String username = ServiceCredentials__c.getValues('BillingServiceCredential').Username__c;         String password = ServiceCredentials__c.getValues('BillingServiceCredential').Password__c;          String auth = username + ':' + password;         String encodedAuth = EncodingUtil.base64Encode(Blob.valueOf(auth));          for(Project__c p : projects) {              BillingServiceProxy.InvoicesPortSoap11 service = new BillingServiceProxy.InvoicesPortSoap11();             service.inputHttpHeaders_x = new Map&lt;String, String&gt;();             service.inputHttpHeaders_x.put('Authorization', 'Basic ' + encodedAuth);              BillingServiceProxy.project project = new BillingServiceProxy.project();             project.username = username;             project.password = password;             project.projectRef = p.ProjectRef__c;             project.billAmount = p.Billable_Amount__c;              if(service.billProject(project).equals('ok')){                 projectsToUpdate.add(new Project__c(ProjectRef__c = p.ProjectRef__c, Status__c = 'Billed'));             }         }         shouldIRun.stopTrigger();         upsert projectsToUpdate ProjectRef__c;     } }   Error     Methods defined as TestMethod do not support Web service callouts   Test Class  @IsTest private class BillingCalloutServiceTest {      @IsTest     private static void testBillingCalloutService() {     Account a = new Account(Name = 'Acme');     insert a;     Opportunity o = new Opportunity(Name='Test', StageName='Submitted Project', AccountId=a.Id, Amount=1000, CloseDate=Date.Today());     insert o;     Project__c p = new Project__c(Status__c='Running',Start_Date__c=Date.Today(),End_Date__c=Date.Today(),Billable_Amount__c=10000,ProjectRef__c='projectX',Opportunity__c=o.Id);     insert p;      insert new ServiceCredentials__c(Name='BillingServiceCredential',Username__c='toto', Password__c='azerty');      Test.startTest();     Test.setMock(HttpCalloutMock.class, new BillingCalloutServiceMock());       p.Status__c = 'Billable';       update p;     Test.stopTest();     // runs callout and check results     p = [select Status__c from Project__c where id =: p.id];     System.assertEquals('Billed', p.Status__c);     }  }
20340
I am trying to use the "navigateToSObject" to redirect to the detail page. But the method $A.get("e.force:navigateToSObject") is always returning null. I dont have a namespace. SO this isn't namespace related issue I assume.  Here is the code of my component  &lt;aura:component &gt; &lt;aura:attribute name="contactName" type="String"&gt;&lt;/aura:attribute&gt; &lt;aura:attribute name="lastName" type="String"&gt;&lt;/aura:attribute&gt; &lt;aura:attribute name="cid" type="String"&gt;&lt;/aura:attribute&gt; &lt;div onclick="{!c.navigateToRecord}" &gt;       &lt;h1&gt;{!v.lastName}&lt;/h1&gt;     &lt;h3&gt;{!v.contactName}&lt;/h3&gt;     &lt;h3&gt;{!v.cid}&lt;/h3&gt; &lt;/div&gt; &lt;/aura:component&gt;   Here is the code of my java-script controller      ({     navigateToRecord : function(component, event, helper){         var cid=component.get("v.cid")        console.log('inside navigateToRecord '+cid);       var navEvent = $A.get("e.force:navigateToSObject");        navEvent.setParams({         "recordId": cid,            "slideDevName": "detail"     });      navEvent.fire();  } })   I am getting null in navEvent hence am not able to set parameters into it. The error is "Uncaught error in $A.run() : Cannot read property 'setParams' of null"
55797
I am new to Apex trying to do some practice assignments and have gotten stuck on this junction object query.  Task: Edit the current getUser() method to do the following:  Return a custom object (that you define in the class) with the current getUser method's query data, and the list of teams the person belongs to (by querying the team assignments).   Parent Object 1: User (Standard Object) Parent Object 2: Team (Custom Object) Junction Object: Team Assignments (Custom Object)    **Original Class &amp; getUser Method** global class CTI {     global class CTIException extends Exception {}      global static User getUser() {          return [SELECT Id, Name, ProfileId, Profile.Name, UserRoleId, UserRole.Name, Username                  FROM User WHERE Id = :UserInfo.getUserId() ];     } }
15895
how can i check wrong id  public with sharing class ContactDetailController {      private ApexPages.StandardController standardController;     public string conId{get;set;}       public ContactDetailController(ApexPages.StandardController standardController)      {        this.standardController = standardController;        conId = ApexPages.CurrentPage().getParameters().get('Id');         if(standardController.getId()==null)         {             ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter Id on the Address Bar'));         }           //this.standardController.addFields(new List&lt;String&gt; {'FirstName','lastname','mobilephone','Accountid','otherphone','title','fax','Department','Email','Birthdate','AssistantName','Reportstoid','Assistantphone','leadsource','OtherStreet','MailingCity','othercity','MailingState','otherstate', });          // getDescribe that retrive whole fields of the particular object         Schema.DescribeSObjectResult r = Contact.sObjectType.getDescribe();         List&lt;String&gt;apiNames =  new list&lt;String&gt;();         for(string apiName : r.fields.getMap().keySet()){             apiNames.add(apiName);         }         System.debug(apiNames);         this.standardController.addFields(apiNames);      }     public PageReference ValidateId()     try{                Id realContId = standardController.getId();                if(Schema.Contact.SObjectType != realContId.getSobjectType())||                {                     ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'Id specified is not an Contact id!'));                     return null;                }          }         catch (Exception e)         {             ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'Bad id specified!'));            return null;          } }      public PageReference Edit()     {         PageReference errorPage = new PageReference('/apex/ContactInsert?id='+conId);         errorPage.setRedirect(true);         return errorPage;     }       public PageReference cloneButton()     {         // Record being cloned         Contact con = (Contact) standardController.getRecord();          // Custom clone logic         Contact clonedcon = new Contact();         clonedcon.FirstName = con.FirstName;         clonedcon.lastName = con.lastName;          clonedcon.mobilephone = con.mobilephone;         clonedcon.Accountid = con.Accountid;         clonedcon.otherphone = con.otherphone;         clonedcon.title = con.title;         clonedcon.fax = con.fax;         clonedcon.Department = con.Department;         clonedcon.Email = con.Email;         clonedcon.Birthdate = con.Birthdate;         clonedcon.AssistantName = con.AssistantName;          clonedcon.Reportstoid = con.Reportstoid;         clonedcon.Assistantphone = con.Assistantphone;         clonedcon.leadsource = con.leadsource;         clonedcon.OtherStreet= con.OtherStreet;         clonedcon.MailingCity = con.MailingCity;         clonedcon.othercity = con.othercity;         clonedcon.MailingState = con.MailingState;         clonedcon.otherstate = con.otherstate;         clonedcon.MailingPostalCode = con.MailingPostalCode;         clonedcon.otherpostalcode = con.otherpostalcode;         clonedcon.MailingCountry = con.MailingCountry;          clonedcon.othercountry = con.othercountry;         clonedcon.Languages__c = con.Languages__c;         clonedcon.Level__c = con.Level__c;         clonedcon.Description= con.Description;          insert clonedcon;         PageReference errorPage = new PageReference('/apex/ContactInsert?id='+conId);          errorPage.setRedirect(true);         return errorPage;           //return new PageReference('/' +clonedcon.id+ '/e' );         // Redirect to the new cloned record         //return new PageReference('/'+clonedcon.Id);         return null;     }  }   getting error     Id value 0012800000CyJVI is not valid for the Contact standard   controller   is there any way to check my Id is correct or not. and show error in VF page using apex:pagemessage
66803
I am trying to call my Apex class from a trigger:  trigger newCrossSellAccounts on Account (before insert) {    crossSellModule.insertAfterAccount2(trigger.new); }   On the class I have:  public void insertAfterAccount2(list&lt;account&gt; accountList){   When I try to save trigger I get error:  Method does not exist or incorrect signature: crossSellModule.insertAfterAccount2(LIST&lt;Account&gt;) at line 2 column 4    Now from  it says .new "Returns a list of the new versions of the sObject records." I tried to change the function on class to:  public void insertAfterAccount2(sObject&lt;account&gt; accountList){   But I get error:  Invalid type: sObject&lt;account&gt;    Should I loop thru and create a list in trigger first? Or is there are workaround. Also, how one would test such trigger/class combination?
44149
I'm experimenting with the  feature, and embedding it in a Visualforce page, from where I hoped I would have some control over the canvas.  Now, the apex:canvasApp has a property called  and it's description says that they're parameters passed to the canvas app.    When I don't use the parameters attribute the canvas page draws normally, and using firebug I can see the call to the ip address of the canvas app. But for it to be useful to me I need to pass some parameters to the canvas page and when I do use the parameters attribute the canvas simply does not show, and in firebug it does not show any call to the ip of the canvas.  How are these parameters passed or how can one catch them? Using firebug, in the call to the ip of the canvas app, I can't see any of the parameters that I'm trying to pass.  Here's the simple code I'm experimenting with:  &lt;apex:page &gt; &lt;apex:canvasApp applicationName="Test Canvas" height="400px" width="750px" parameters="{vst_cli: '1293'}" /&gt; &lt;/apex:page&gt;   Inside the parameters attribute I've tried some different things: "{vst_cli: '1293'}" "{vst_cli: 1293}" "{'vst_cli': '1293'}" All of which had the same effect.  Any help or pointers will be welcome.  Thanks in advance.
113237
I am running a soql query to obtain the value of a specific field from a custom object and it is returning the ID of the record on the visualforce page instead of the field value that I need it to return, the specific query I am having issues with is the Names query on the very bottom. If anyone has any ideas why it's returning the ID of the record instead of the specific field value please let me know.   patient_name__c is the field name that I need to obtain the value from and lead__c is a custom object that we have created.       public without sharing class LeadAlertController {     public integer leads {get;set;}     public integer overleads {get;set;}     public List&lt;lead__c&gt; Names {get;set;}         public LeadAlertController() {         leads = [select count() from lead__c where lead_status__c=:'Not Attempted'];         overleads=[select count() from lead__c where lead_status__c=:'Not Attempted' AND x10MinAlert__c=:true];         Names = [select patient_name__c from lead__c where lead_status__c=:'Not Attempted'];       } }   Here is my VF Page  &lt;apex:page controller="LeadAlertController" showHeader="false" sidebar="false" standardStylesheets="false"&gt; &lt;!-- Begin Default Content REMOVE THIS --&gt; &lt;meta http-equiv="refresh" content="10"/&gt; &lt;style&gt; td{     border: 1px ;     border-style: solid; } &lt;/style&gt; &lt;table align="center" style="width:100%;border:1px solid"&gt;     &lt;tr&gt;         &lt;td align="center"&gt;             &lt;h3&gt;Number of Hot Leads&lt;/h3&gt;         &lt;/td&gt;         &lt;td align="center"&gt;             &lt;h3&gt;Number of Hot Leads Over 10 Minutes&lt;/h3&gt;         &lt;/td&gt;          &lt;td align="center"&gt;             &lt;h3&gt;List of Names&lt;/h3&gt;         &lt;/td&gt;     &lt;/tr&gt;     &lt;tr&gt;         &lt;td align="center"&gt;             &lt;h1&gt;{!Leads}&lt;/h1&gt;         &lt;/td&gt;         &lt;td align="center"&gt;             &lt;h1&gt;{!OverLeads}&lt;/h1&gt;         &lt;/td&gt;          &lt;td align="center"&gt;             &lt;h1&gt;{!Names}&lt;/h1&gt;         &lt;/td&gt;     &lt;/tr&gt; &lt;/table&gt;  &lt;apex:outputPanel rendered="{!if(OverLeads&gt;0,true,false)}"&gt;     &lt;audio src="/resource/alert" type="audio/mp3" autoPlay="true"&gt;     &lt;/audio&gt; &lt;/apex:outputPanel&gt;
43162
I have two different @wire methods that are calling Apex methods to get different results from two different objects.  After this information has been retrieved by each @wire respectively, I'd like to afterwards compare the results and set a few other attributes on the page.  How do I achieve this?  Should I use connectedCallback() or renderedCallback() or neither?  Is there a better way to do multiple Apex method calls then process them afterwards within the JS when the component loads?  I'm hoping there's a graceful way to accomplish this in LWC without having to chain Promises, or having to handle all of this within a single Apex method call.
23417
I am loading a JavaScript object between Lightning Components   var model = {} model.user = {} model.caller = {} model.caller.name = 'Batman'; model.other = {} // etc   And then into component attributes.  &lt;aura:attribute name="model" type="Object" /&gt; &lt;aura:attribute name="caller" type="Object" /&gt;  cmp.set("v.model", model); cmp.set("v.caller", model.caller);   Then I use then like this:  &lt;lightning:input value="{!v.caller.name }" label="Caller name" /&gt;   Then I get data back out:  model.caller = cmp.get("v.caller");      My question is:  Why do my JavaScript object sub-objects sometimes get set to Proxy when I inspect them in the console:  caller: Proxy [[Handler]]: e [[Target]]: Object [[IsRevoked]]: false   And other times I get the values I expect...  caller { name : "Bruce Wayne" }
109364
I have a method which takes params object[] such as:  void Foo(params object[] items) {     Console.WriteLine(items[0]); }   When I pass two object arrays to this method, it works fine:  Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } ); // Output: System.Object[]   But when I pass a single object[], it does not take my object[] as the first param, instead it takes its all elements like I wanted to pass them one by one:  Foo(new object[]{ (object)"1", (object)"2" }); // Output: 1, expected: System.Object[]   How do I pass a single object[] as a first argument to a params array?
112048
Background  I'm using  to update some picklist values on the fly. (i.e. Every time a record is inserted/updated/deleted in Table A, I'm adding/subtracting picklist values into a MultiselectePicklist in table B).  Since,     An Apex trigger can execute a callout when the callout is invoked within a method defined as asynchronous: that is, defined with the @future keyword.   I implemented a method with the future annotation, and      For Apex code that is executed asynchronously, such as @future methods, Batch Apex jobs, or scheduled Apex jobs, getSessionId returns null.   so, I needed to pass the session Id as a parameter in the method, I implemented something like:  @future (callout=true) public static void addContactPicklistPreference(List&lt;String&gt; preferences, String sessionId){     Schema.DescribeSObjectResult sObjectDescribe = Contact.sObjectType.getDescribe();     String picklistFieldName = 'Preference__c';                    Picklist_MDT.addPicklistValues(sObjectDescribe, picklistFieldName, artists, sessionId); }  public class Picklist_MDT {      public static void addPicklistValues(Schema.DescribeSObjectResult sObjectDescribe, String picklistFieldName, List&lt;String&gt; picklistValueNames, String sessionId) {         MetadataService.MetadataPort service = createService(sessionId);         ...         }       public static MetadataService.MetadataPort createService(String sessionId) {         MetadataService.MetadataPort service = new MetadataService.MetadataPort();         service.SessionHeader = new MetadataService.SessionHeader_element();         service.SessionHeader.sessionId = sessionId;         return service;     } }   And called the addContactPicklistPreference method from trigger context passing it the UserInfo.getSessionId() value.   Problem  This worked just fine in salesforce classic but not in lightning, when it triggers in lightning I'm getting System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: INVALID_SESSION_ID.... Funny thing is that if I put a System.debug(UserInfo.getSessionId()); before calling the addContactPicklistPreference method it prints a valid session Id in both classic and lightning.  I would really appreciate any input about this.
16290
This is a canonical question and answer developed by the community to help address common questions. If you've been directed here, or your question has been closed as a duplicate, please look through the resources here and use them to shape more specific questions. To browse all canonical questions and answers, navigate to the  tag. This question and answer is owned by the community! If you can improve it and make it more useful, you're welcome to edit it. I am building a trigger, a unit test, or other Apex code. I'm working with sObject records, and trying to access related record information. For example, I might have a structure like this: Account a = new Account(Name = 'Test'); insert a;  Opportunity o = new Opportunity(Name = 'Donation', AccountId = a.Id); insert o;  System.assertEquals(o.Account.Name, 'Test', 'Correct Account associated'); // Assertion fails!  Or, in a trigger, I might be aiming for something like this: trigger ContactTrigger on Contact (after insert) {     for (Contact c : Trigger.new) {         if (c.Account.Name == 'Test') {             // Take some action here         }      } }  Why doesn't this work? Why am I getting null values, or NullPointerExceptions?
8344
I'm working with a bit of html and Javascript code that I've taken over from someone else. The page reloads a table of data (via an asynchronous request) every ten seconds, and then re-builds the table using some DOM code. The code in question looks something like this:  var blah = xmlres.getElementsByTagName('blah'); for(var i = 0; i &lt; blah.length; i++) {     var td = document.createElement('td');     var select = document.createElement('select');     select.setAttribute("...", "...");     select.onchange = function() {         onStatusChanged(select, callid, anotherid);     };     td.appendChild(select); }   When the onchange event is fired for a &lt;select&gt; element however, it seems like the same values are being passed to the onStatusChanged() method for every &lt;select&gt; in the table (I've verified that in each iteration of the loop, callid and anotherid are being given new, distinct values).   I suspect this is occuring because of the nature of how I am setting the event handler, with the select.onchange = function() syntax. If I understand how this is working correctly, this syntax sets a closure for the onchange event to be a function which refers to these two references, which end up having a final value of whatever they are set to on the last iteration of the loop. When the event fires, the value referenced by callid and anotherid is the value set in the last iteration, not the value set at the individual iteration.  Is there a way that I can copy the value of the parameters I am passing to onStatusChanged()?  I've changed the title to better reflect the question and the accepted answer.