Udders Udders - 1 year ago 67
Javascript Question

Show/hide fields depending on select value

I am trying to show and hide a few form fields depending on the value of one of my select fields. I am looking to use arrays to hold what should be shown and what should not be shown for each select value, to save me from a massive switch statement, but cannot figure out how to do it.

I am using PHP and jQuery. Any help would be great.

Answer Source

Try something like this:

<select id="viewSelector">
   <option value="0">-- Select a View --</option>       
   <option value="view1">view1</option>
   <option value="view2">view2</option>
   <option value="view3">view3</option>

<div id="view1">
  <!-- content --> 
<div id="view2a">
  <!-- content --> 
<div id="view2b">
  <!-- content --> 
<div id="view3">
  <!-- content --> 

then in the jQuery:

$(document).ready(function() {
  $.viewMap = {
    '0' : $([]),
    'view1' : $('#view1'),
    'view2' : $('#view2a, #view2b'),
    'view3' : $('#view3')

  $('#viewSelector').change(function() {
    // hide all
    $.each($.viewMap, function() { this.hide(); });
    // show current
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download