1

When I click GOOGLE1 button, the url is opened in a new window. But when GOOGLE2 is clicked, the page just refreshes. I'm missing something?

<apex:page >
    <apex:form>
        <apex:pageBlock>
            <apex:pageBlockButtons>
                <apex:commandButton value="GOOGLE1" onclick="window.open('https://google.com');"/>
                <apex:commandButton value="GOOGLE2" onclick="ToGoogle();"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
    <script>
    function ToGoogle() {
        window.location.href="https://google.com";
    }
    </script>
</apex:page>

Thanks in advance.

1 Answer 1

2

The click causes the page's controller to fire (it's a form submit), interrupting the attempt to go to Google. If you change your code to onclick="ToGoogle(); return false;", the default behavior (the page controller firing) will be cancelled, and the browser will go to Google instead. You could also pass an event object into your function and use event.preventDefault() to keep the form from submitting on all modern browsers. Behind the scenes, you should note that GOOGLE1 actually loads two pages-- Google, plus a reload of your Visualforce page. You would do well to return false; in that onclick handler as well.

2
  • Thank you @sfdcfox. Command buttons can occur only within form. So whenever we want a command button to open an external site, while invoking javascript we need to return false to block controller firing or to pass an event object to prevent form submission. Understood.
    – user16455
    Commented Jan 17, 2015 at 0:49
  • 2
    However, I suppose I should also have mentioned: whenever I don't intend to interact with the controller, I usually use a regular <input type="button" style="btn" />, to avoid the view state size penalty. You can use regular buttons in Visualforce, just as you can use any other regular HTML.
    – sfdcfox
    Commented Jan 17, 2015 at 0:55

You must log in to answer this question.

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