views:

44

answers:

2

Hi, jquery masters,

I have a select box with values: apple-80 apple-100 apple-120 apple-300

I have: <body class="fruit apple-120 otherclass anotherclass">

I want to manipulate the body class "apple-120" to get replaced by any of selected value from the select box while keeping the fruit, otherclass, anotherclass, class untouched.

So far I created this:

$.fn.classSwitcher = function(options) {
  var baseOptions = {
    classTarget: 'body',
    oldClass: 'apple-120'
    };

  var options = $.extend(baseOptions, options);

  return this.each(function() {
         $(this).click(function() { 
           var t = $(this);
           var optionVal = t.val();
             $(options.classTarget).removeClass(options.oldClass).addClass(optionVal);
         });
  });
};

Then I have:

$('#sel option').classSwitcher();

This replaced the class, but on the next click of the select box, more select option values are added as new classes, which was not what I wanted.

I just want to replace "apple-120" with a new value, not adding more. Any other click will just replace the same target class.

Plus, I also wanted to grab all select box values to keep them as a condition to narrow down selection on those classes. Says, if a class matches any of the values in the select box, do something.

Any hint would be very much appreciated. Thanks.

+3  A: 

The problem is that you are not updating options.oldClass so it always tries to remove the original apple-120. You should set it to the class that's being assigned when you update:

...
     $(this).click(function() { 
       var t = $(this);
       var optionVal = t.val();
       $(options.classTarget).removeClass(options.oldClass).addClass(optionVal);
       options.oldClass = optionVal;
     });
...
Max Shawabkeh
Hi, Max. You addressed my problem. I mistook it fot Lachlan. The answers are jumping around too :) Any hint on grabbing all select box values too? Thanks
swan
Thanks Max, marking this fixed. Love this community.
swan
I'm not sure what you mean by grabbing select box values. You can simply get all the `<option>` elements via `$('#sel option').toArray()` then get their `.value`.
Max Shawabkeh
A: 

If you want to remember values from previous invocations of click, you could store the value with data()

$(this).click(function() { 
     var val = $(this).val();
     if (val != $(this).data('previous')) {
         $(this).data('previous', val );
         // ...
     }
});
Lachlan Roche
This one works so far, just missing the closing ). I'll update my finding with other answer. Thanks.
swan
Oops, wrong pick. Your code actually broke. Any hint? I tested along with Max answers and mistook it for you and cache as usual.
swan