简体   繁体   中英

jQuery add remove classes in select box and buttons

I have two select boxes and a few buttons as post category filters. Check out my Fiidle . I want to add a background color when I click any of the buttons or select boxes and remove it when I click another. The effect is exactly the same as in this example .

I guess I have to register a change event on the select box. However, as a beginner, all I can come up with is mincing this code

$selectors.change(function() 
{
     var $selector = $(this);
     var cat = $selector.data('product-collection__category');
     $selectors.removeClass('product-collection__selector--active');
     $selector.addClass('product-collection__selector--active');
});

and turning it into this invalid code

$selectors.change(function() 
{
     var $selector = $(this);
     var cat = $selector.find('option:selected').data('product-collection__category');
     $selectors.removeClass('filterselect__selector--active');
     $selector.addClass('filterselect__selector--active'); 
});

Would anyone please show me how to get this to work?

Just add below css for effect.

.product-collection__selector:hover {
    background: green;
}
.product-collection__selector {
    -webkit-transition:background-color 0.3s ease-in;
    -moz-transition:background-color 0.3s ease-in;
    -o-transition:background-color 0.3s ease-in;
    transition:background-color 0.3s ease-in;
}  

JS Change

replace

var $dropdown = $collection.find('.filterselect');

 var $selectors = $collection.find('.product-collection__selector,.filterselect__selector');

with

var $selectors = $collection.find('.filterselect');  

Add below code in your change event to remove active class from li

$collection.find('li').removeClass('product-collection__selector--active');

Updated DEMO

EDIT ANSWER

Don't need to replace as above just add below two line code. and make changes as below:

var $dropdown = $collection.find('.filterselect');
var $selectors = $collection.find('.product-collection__selector,.filterselect__selector');  

replace

$selectors.change(function () 
AND
$selectors.removeClass('filterselect__selector--active');

with

$dropdown.change(function ()
AND
$dropdown.removeClass('filterselect__selector--active');

NEW UPDATED FIDDLE

The FIDDLE solves the problem of background color. Onchange event works on select node and not on options. Also there was not much requirement applying .each on the container div.

var $selectors = $('select.filterselect');

You can use jQuery node traversal, .parent, .parents, .children, .find methods to locate the nearest container in which you want to modify the data based on the select box which is changed.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM