[SalesForce] Set value of apex:attribute from javascript

I have a custom component(named myComponent) which has an attribute value. I want to change the value of this attribute using javascript. How to do that ?

<apex:component >
    <apex:attribute name="value" description="The value of picklist"
                    type="String[]" />
    <script>
       //change value of attribute here
       var x = {!value}
       x = ['val1', 'val2']
    </script>

</apex:component >

visulaforce page:

<apex:form>
    <c:myComponent value={!value}></<c:myComponent>
    <apex:commandButton Value="Post"/>
</apex:form>

When I click the Post button, the value is not updated in the controller.

Best Answer

Are you trying to send a value modified into your component to your controller ?

If so, check this:

  1. You should set the action to call in your apex:commandButton
  2. You should set the component attribute to an apex:inputField in order to sent it using an standard apex:form to the controller.
  3. Instead that you could invoke your controller method by javascript directly by using @RemoteAction
  4. Also, you should use the function JSENCODE to escape x = {!value};

This is an small sample of the last option:

 var x = {!JSENCODE(value)};

    Visualforce.remoting.Manager.invokeAction(
        '{!$RemoteAction.MyController.sentMyValue}', 
        x, 
        function(result, event){
            console.log(result);
        }, 
        {escape: true}
    );