Use Cases of JavaScript in Salesforce: Hide & Show Page Block

Use Cases of JavaScript in Salesforce: Hide & Show Page Block

 

JavaScript is used as a client side scripting language, which means that JS code is written into an HTML page or with other back-end languages to create a dynamic UI. So, when a user requests a web page with JavaScript in it, the script is sent to the browser and it’s up to the browser to do something with it. JavaScript scripts are read, interpreted and executed at the client-side itself. Using Javascript with Salesforce is similar to what is used with other languages. Visualforce pages can be a combination of apex, html, css and javascripts.

 

What does this code do?

The code snippet below is used in Salesforce Visualforce page to hide and show page blocks. Three page blocks are present on the same page and only one block is visible at a time. Instead of navigating the user to the next webpage, the required page blocks are displayed on a single page as per the requirement.

 

[WPGP gif_id=”18324″ width=”500″]

 

When it can be used?

 

When you don’t want the data to be saved into the database and navigating to a different page will lose the data in the view-state, this code becomes handy. It will allow user to access data from view state thus reducing the hassle of creating temporary code variables to store values.

 

Code Snippet:

 

<script> 
    
   // Hide User Details section on Next button Click
    
function HideSection() 
    {
        var x = document.getElementById("pageid:formid:pageblockId");
        var y = document.getElementById("pageid:formid:selectproduct"); 
        
        if (x.style.display === 'none') 
        {
            x.style.display = 'block';
            y.style.display = 'none';
        } 
        
else
        {
            x.style.display = 'none';
            y.style.display = 'block';
        }
    }

    // Hide Select Products section on Select button Click
      
function HideProductSection() 
    {
        var x = document.getElementById("pageid:formid:pageblockId");
        var y = document.getElementById("pageid:formid:selectproduct"); 
        
        if (y.style.display === 'none') 
        {
            y.style.display = 'block';
            x.style.display = 'none';
        } 
        else 
        {
            y.style.display = 'none';
            x.style.display = 'none';
        }
    }
    
    // Hide all sections except User Details on Page Load
    
window.onload = function() 
    {   
        var x = document.getElementById("pageid:formid:pageblockId");
        x.style.display='block'; 
        
        document.getElementById("pageid:formid:selectproduct").style.display='none';
        
    } 
    </script>
    

 

Leave a Reply

Close Menu
Top