Create a single change function for multiple CSS selectors in Jquery

0

Use the function below to add CSS classes (blue, red, pink ...) in a ".container" DIV from a select "#selcolor". Is it possible for me to use this same function in other select tags with different IDs? In this case the classes (blue, red, pink ...) would not be added in the ".container" DIV, ie the "div_action" variable of the function would have to be modified.

  function select_changed() {
    jQuery('select#selcolor').each(function() {
      var selected = jQuery(this).val();
      var div_action = '.container';
      if(selected == '') {
        jQuery(div_action).addClass('');
      } 
      if(selected == 'blue') {
        jQuery(div_action).addClass('blue');
      } else {
        jQuery(div_action).removeClass('blue');
      }
      if(selected == 'pink') {
        jQuery(div_action).addClass('pink');
      } else {
        jQuery(div_action).removeClass('pink');
      };
      if(selected == 'red') {
        jQuery(div_action).addClass('red');
      } else {
        jQuery(div_action).removeClass('red');
      };
    });
  }
  $('select#selcolor').change(function() {
    select_changed();
  });
    
asked by anonymous 28.03.2016 / 05:52

1 answer

2

There are several ways to do it.

One option is to use a parameter in the select_changed function to define what the target element is:

function select_changed(target){
    jQuery('select#selcolor').each(function() {
      var selected = jQuery(this).val();
      if(selected == '') {
        jQuery(target).addClass('');
      } 
      if(selected == 'blue') {
        jQuery(target).addClass('blue');
      } else {
        jQuery(target).removeClass('blue');
      }
      if(selected == 'pink') {
        jQuery(target).addClass('pink');
      } else {
        jQuery(target).removeClass('pink');
      };
      if(selected == 'red') {
        jQuery(target).addClass('red');
      } else {
        jQuery(target).removeClass('red');
      };
    });
}

$('select#selcolor').change(function() {
  select_changed('.container');
});

$('select#selcolor').change(function() {
  select_changed('.outro-container');
});
    
28.03.2016 / 06:07