1

Just wondering how I can use the value of a javascript variable to conditionally render a button like the code below.

<script>
    var buttonShown = FALSE;

    function ShowButton() {
        buttonShown = TRUE;
    }
</script>

<apex:commandButton onclick="ShowButton()"/>
<apex:commandButton action="{!DoSomething}" rendered="buttonShown"/>

I'm not quite sure how to get the boolean value into that last line. Any suggestions are appreciated!

4
  • Just curious why are you still writing or maintaining any UI in Visualforce? If you stick with this technology, you'll want to show/hide how you would if you were using vanilla HTML/JS, except your query selectors change slightly.
    – Adrian Larson
    Commented Dec 6, 2021 at 14:43
  • What is the modern standard for maintaining UI? I'm fairly new to using Salesforce, so far I've only built a few "Flows" and Visualforce Pages with Apex controllers.
    – Kylan Vike
    Commented Dec 6, 2021 at 14:49
  • You should very strongly consider Lightning Web Components, which are the present and future of UI on the platform. While Visualforce still has a place, it is basically only appropriate to use for email templates. Otherwise, it's considered a bit archaic.
    – Adrian Larson
    Commented Dec 6, 2021 at 14:52
  • That's great to know! Thanks for the suggestion, Adrian.
    – Kylan Vike
    Commented Dec 6, 2021 at 15:06

2 Answers 2

1

I wouldn't spend too much time figuring out how to do this type of thing in the best way. A much more efficient investment of your time would be in learning how to instead use Lightning Web Components, which are the present and future of UI development on the platform. They also make this type of question exceedingly simple to solve, as you would just bind directly to a variable on your Javascript controller.

<template if:true={myVariable}>
    <!-- button markup -->
</template>
0

Your goal, as stated, is impossible with Visualforce.

Visualforce markup is processed on the Salesforce side (i.e. server-side) to transform it into HTML, which then gets sent to your browser.

Javascript is executed on the client side (i.e. your browser), so by the time your Javascript executes, Salesforce has already made its decision as to whether or not the button should be rendered.

You could still use client-side techniques to alter the page such as:

  • Using Javascript to set a CSS class on the rendered button to hide it (visibility:hidden)
  • Using Javascript to add the disabled attribute to the rendered button (simply having the attribute causes browsers to make the button gray and prevent it from being clicked, I believe)

Both of those solutions would require you to set the id attribute in your Visualforce (so that you can target the specific button in Javascript).

You must log in to answer this question.

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