Search code examples
javascriptfacebookfbjs

Change HTML SELECT OPTIONs using a json object in FBJS


I have a html select input with a default set of options (it has an ID). I also have a json object that looks like

var replacement_options = {'value 1':'display 1', 'value 2':'display 2' ....

How would I replace the options in the select with the values and displays from the json object using Facebook JS? (FBJS)


Solution

  • After piecing some stuff together, I was able to create a function to do this.

        //accepts a object for options {value1:display1, value2:display2...
        function updateSelectOptionsWithJSON(element_id, options, first_display, first_value)
        {
                var choiceList = document.getElementById(element_id);
                for(var count = choiceList.getOptions().length - 1; count > -1; count--)
                {
                        var node = choiceList.getOptions()[count];
                        choiceList.removeChild(node);
                }
                //you can remove these next 4 lines and the last two parameters of this function
                //if you just want options to come from the secton parameter
                var node =  document.createElement('option');
                node.setTextValue(first_display);
                node.setValue(first_value);
                choiceList.appendChild(node);
    
                for(key in options)
                {
                        var node =  document.createElement('option');
                        node.setTextValue(options[key]);
                        node.setValue(key);
                        choiceList.appendChild(node);
                }
        }