6

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;}
}
4
  • Anything in the browser's JavaScript console?
    – Mike Chale
    Nov 21, 2013 at 16:15
  • @MikeChale Nothing but a mocking caret. Nov 21, 2013 at 16:22
  • 2
    You need to add onclick="JSetString(); return false;" to your call and remove rerender="panel" parameter. Nov 21, 2013 at 17:13
  • @mast0r That did it! Thanks very much :-) Nov 22, 2013 at 1:23

1 Answer 1

4

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .