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.
Best Answer
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 useevent.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 toreturn false;
in that onclick handler as well.