0

Can some spot what I am doing wrong in the code below please? I know it's not the most elegant code, but I am doing five things at the moment and thought I could knock this easy one out quickly to get it off my plate.

All I want to do is>> if project type selected equals a particular value, show a fieldset, if it does not equal that value, hide the fieldset. Pretty simple right? I can't get the fieldset to hide if the value selected does not match.

Mind you, I am new to jquery, but this is a basic if/else - what am I doing wrong here? Thank you in advance.

$('fieldset#section-841', 'fieldset#section-837' ).hide();
var DM_projtype = new Array(
        {value : 'Direct Mail', sect_id : 'fieldset#section-841'},
        {value : 'Multiple items', sect_id : 'fieldset#section-837'}
    );
$('select#3596').change(function() {
    var getDM_projType = $(this).val();
    var sect_id = '';
     for (var i = 0; i < DM_projtype.length; ++i) 
        {
            if (DM_projtype[i].value == "Direct Mail" )
                {
                    sect_id = DM_projtype[i].sect_id;
                   $(sect_id).show();
                }
            else
                {
                   $('fieldset#section-841').hide(); 
                }
            if (DM_projtype[i].value == "Multiple items" )
                {
                    sect_id = DM_projtype[i].sect_id;
                   $(sect_id).show();
                }
            else
                {
                   $('fieldset#section-837').hide(); 
                }
       }
  });
Patricia
  • 7,752
  • 4
  • 37
  • 70
user1176783
  • 673
  • 4
  • 19
  • 39
  • 2
    Use a debugger to step through your code. – Matt Ball Apr 24 '12 at 15:04
  • you don't need to do things like select#3596 id selectors are the fastest, so you can just do #3596, same with your fieldset selectors. i don't think that's the problem. Your id's are invalid. see this questions: http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html – Patricia Apr 24 '12 at 15:07

1 Answers1

2

You have structured your code against logic it seems - each element of your array is going to be processed through the loop, so you execute both an if and else of each block set you contain. You should instead do this:

$('select#3596').on('change', function() // do .change() if using a lower jQuery version
{
    var thisVal = $(this).val(); // Assuming this returns 'Direct Mail' or 'Multiple Items'

    $(DM_projtype).each(function()
    {
         $(this.sect_id).hide();

         if(this.value == thisVal)
            $(this.sect_id).show();
    });
});
Tejs
  • 40,736
  • 10
  • 68
  • 86
  • Good grief - THANK YOU Tejs - that was works exactly the way I want it to and thank you for the explanation of what I was doing wrong. – user1176783 Apr 24 '12 at 15:19