Search code examples
jquerytoggleclass

Get values from select options - use values to toggleClass()


I have a select box with a number of options. Each option represents a class name that can be selected and added to a div. The div may already have other classes which are not to be touched.

My issue is that I would like to toggle between these classes only - not just keep adding new ones. How can I create a script that loops through all the class names of the select box and toggles between them?

Here's what I have - i just adds classes - it doesn't toggle.

html:

<form id="form">
  <div>
    <label for="height">Height:</label>
    <select id="height">
      <option>- Select class -</option>
      <option value="height133">133</option>
      <option value="height55">55</option>
      <option value="otherclass">127</option>
    </select>
  </div>
  <button type="button" id="go">Submit</button>
</form>
<div class="gridbox otherclass1 otherclass2">
  <div></div>
</div> 

jQuery:

$("#go").click(function() {
   var height = $("#height").find(":selected").val();
   $(".gridbox").toggleClass(height);
});

Fiddle here.

Thanks a lot in advance.


Solution

  • You need to remove other classes which were added earlier.

    $("#go").click(function() {
        var heightElem = $("#height");
        var height = heightElem.find("option[value]:selected").val();
        var allClassess = heightElem.find("option[value]") //traverse to all option elements
            .map(function() {
                return this.value ? this.value : null;
            }).get() // Get an array of all the class
            .join(' ') //Create a string;
        $(".gridbox").removeClass(allClassess).addClass(height);
    });
    

    DEMO