[SalesForce] js remoting result returning selectOption

i wanted to know how to separate the selectOption value and lable in the result returned by js remoting function.
i have a js remote function in apex page:

<script>
    function sayhello()
    {
         Visualforce.remoting.Manager.invokeAction(
        '{!$RemoteAction.Myctrl.sayHello2}',
        function(result, event){
            if(event.status) 
            {
                alert(result);
                 var txt= jQuery("[id$=someList]").val();
                alert(txt);
                //need to segregate result into value and label
                var opt = new Option(result); 
                jQuery("[id$=someList]").append(opt); 
                }
            else alert("error");
        });
    }

<apex:selectList id="someList" value="{!selectedContentId}" >
    <apex:actionSupport event="onchange" action="{!doSearch}" reRender="block1" />
     <apex:selectoption id="none" itemValue="red" itemLabel="Red" />
</apex:selectList>

controller remote action:

@RemoteAction
global static SelectOption sayHello2()
{  
      return (new SelectOption('value','label''));
}

I need to know how to extract the label part from the result returned.

Best Answer

The default behaviour when returning a SelectOption from a Remote Action is to return a String with the value in it.

If you need to return the label as well then you need to create a wrapper class with exposes the label and return that instead. You'll then be able to access the label property in the JSON object that is returned.

public class SelectOptionWrapper
{        
    public String label { get; set; }
    public String value { get; set; }

    public SelectOptionWrapper(SelectOption o)
    {
        label = o.getLabel();
        value = o.getValue();
    }
}

@RemoteAction
public static SelectOptionWrapper getSelectOption()
{  
      return new SelectOptionWrapper(new SelectOption('test','label'));
}
Related Topic