For example, let's say you have 8 sections to hide/show and depending on the value of a dropdown, you have to show or hide dynamically from 1 to 8 sections.

1) Is there any better way of doing this than with the approach of the code below?
2) Is this approach acceptable?


  var value = this.value;
  var $section1 = $("#section1");
  var $section2 = $("#section2");
  var $section3 = $("#section3");

  $(".section").hide(); //hides all sections

  if(value == "someValue"){
  } else if (value == "someOtherValue") {
  } else {


Any other advice that you consider helpful will be appreciated.


While not really a pattern per se, the main thing I'd do here is separate the code from the data.

By "data", I mean which sections should be shown or hidden for each dropdown item.

var sectionsToShow = {
   item1: [1, 2, 3],
   item2: [2],
   item3: [6, 4, 5],

Then your dropdown handler can (ideally) do something like

sectionsToShow[this.value].forEach(function(sectionToShow) {

to show whichever sections are appropriate for that item.

This way it's much, much easier to reconfigure what sections are shown for each item when you inevitably have to change that mapping somehow.

  • Of course, AngularJS would make that very, very simple. No if ... then code, just an ng-show or ng-hide on each HTML element. – Mawg says reinstate Monica Jun 2 '15 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.