Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I'm trying to set a variable inside my controller via an actionFunction, which is called by some Javascript, which is initially called by either by an actionPanel (with styleClass='btn') or a commandButton.

If the caller is the actionPanel then the variable updates reliably. However with the commandButton I can see the updated value flash briefly before reverting to its previous value. Maybe one out of every six clicks of the button actually causes the new value to stick. Sometimes it can take a dozen or more tries, regardless of click frequency.

Can someone please explain what's going on here?

PAGE

<apex:page controller="MyController">
    <apex:form >
        <apex:outputPanel id="panel">
            <apex:outputText value="MyString = {!MyString}"/>
            <apex:actionFunction name="SetString" rerender="panel">
                <apex:param name="param1" value="" assignTo="{!MyString}"/>
            </apex:actionFunction>
            <script>
                function JSetString() {
                    SetString('{!MyString}' + '.');
                }
            </script>
            <apex:outputPanel onclick="JSetString()" styleClass="btn">
                Grow {!MyString} (works)
            </apex:outputPanel>
            <apex:commandButton onclick="JSetString()" value="Grow {!MyString} (unreliable)" rerender="panel"/>
        </apex:outputPanel>
    </apex:form>
</apex:page>

CONTROLLER

global class MyController {

    public MyController() { MyString = 'hello'; }

    public String MyString {get;set;}
}
share|improve this question
    
Anything in the browser's JavaScript console? –  Mike Chale Nov 21 '13 at 16:15
    
@MikeChale Nothing but a mocking caret. –  Gary Chapman Nov 21 '13 at 16:22
2  
You need to add onclick="JSetString(); return false;" to your call and remove rerender="panel" parameter. –  mast0r Nov 21 '13 at 17:13
    
@mast0r That did it! Thanks very much :-) –  Gary Chapman Nov 22 '13 at 1:23

1 Answer 1

up vote 4 down vote accepted

Command buttons translate to form input submit buttons. Hence they have a default behavior to submit the form when clicked, which is conflicting with your javascript call. If you change the call to onclick="JSetString(); return false;" as @mast0r pointed out the return false prevents the onclick event from bubbling up to the form and should fix your issues. Removing the rerender on the command button also can't hurt since you're action function already has that.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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