1

I am using a VF page to get the contents of a picklist and to display it on the page so a user can select a certain value and follow on with a case creation wizard....

I know I can do this with VF code:

<apex:form >
    <apex:inputField value="{!case.GC_Country__c}" />
</apex:form>

I am just trying to build my knowledge of Salesforce and JS and how you can interact with them both.

(function() {
                sforce.connection.sessionId = '{!$Api.Session_ID}';
                var describeResults = sforce.connection.describeSObject("Case");
                var select = document.getElementById("yourSelect");
                for (var i = 0; i < describeResults.fields.length; i++) {
                    var fieldList = describeResults.fields[i];
                    if (fieldList.label == 'Country') {
                        var values = fieldList.picklistValues;
                        for (var j = 0; j < values.length; j++) {
                            var el = document.createElement("option");
                            el.textContent = values[j].label;
                            el.value = values[j].value;
                            select.appendChild(el)
                        }
                        break;
                    }

                }
            })();

But I keep on getting the following: Uncaught TypeError: Cannot read property 'appendChild' of null

However, whenever I run the command from the JS console in Chrome it executes correctly and the picklist is built instantly :/

  • 1
    Is this script at the top or bottom of the page? Probably you have placed the script at the top of the page which will cause the script to run (as this is a IIFE) before the select element is available in the DOM. Can you move the script to the end of the page and try again. – Sam Jan 21 '15 at 10:30
  • That worked :D Thanks! I should have realised that in the first place -_- – Timothy Jan 21 '15 at 11:25
  • Reply with an answer and I will mark it up and tag it as the correct answer :) – Timothy Jan 21 '15 at 11:26
1

The reason you're getting the error is because the script is placed at the top of the page and by the time javascript is parsed, the DOM would not have been loaded in first place. Moving your script to the bottom of the page would resolve the issue. Also it improves the performance of the page when you move the script to the bottom of the page. You can read about it here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.