HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Expandable text boxes for legends of fieldsets

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
boxestextexpandablefieldsetslegendsfor

Problem

What is the best way to refactor the following script?


    $(document).ready(function() {
        $(".rolesList").hide(); 
    });

        $("#legendFunction").click(function() {
        $("#divChkUserRoles").toggle('slow');            
            var text = $("#lblExpandFunction").text() == '+' ? '-' : '+';
            $("#lblExpandFunction").text(text);
        })

        $("#legendMISheet").click(function() {
        $("#divChkUserRolesMISheet").toggle('slow');
            var text = $("#lblExpandMISheet").text() == '+' ? '-' : '+';
            $("#lblExpandMISheet").text(text);
        })


The above script will be applied to the following HTML and ASP.NET code:


                
                    +
                    KengLink Function 
                
                      
                                      
                
            
            
                
                    +
                MI Sheet
                
                  
                    
                
            

Solution

Don't use ids at all. (You almost never should be using them. Ids get to be really problematic once you have composite views and/or multiple people on a project)

Place a few appropriate classes in your html. And use the jquery composite and relative references to do it all at once.

$('.expander').click(function() {
  $(this).closest('fieldset').find('.expandable').toggle('show');
  var l = $(this).find('label');
  l.text(l.text() === '+' ? '-' : '+');
});


where your clicker span gets a class of expander and your rolesList gets the class of expandable. You could just use rolesList directly, but I find expandable to be somewhat more descriptive.

Code Snippets

$('.expander').click(function() {
  $(this).closest('fieldset').find('.expandable').toggle('show');
  var l = $(this).find('label');
  l.text(l.text() === '+' ? '-' : '+');
});

Context

StackExchange Code Review Q#10361, answer score: 3

Revisions (0)

No revisions yet.