David
David

Reputation: 224

'fadeToggle' multiple div tags via drop down menu

I need to be able to hide/show multiple div tags on the same page via a drop down menu, but I want them to use the jQuery 'fadeToggle'. I can easily do this without 'fadeToggle' by using the following code:

function generateTask() {
     document.getElementById('football').style.display = 'none'; 
     document.getElementById('football2').style.display = 'none';
}

html:

     <select name="something" id="something">
       <option value="1" onclick="generateTask();">Football</option>
       <option value="2" onclick="generateTask();">Cricket</option>
       <option value="3" onclick="generateTask();">Baseball</option>
     </select>


    <div id="football">balls</div>
    <div id="football2">shorts</div>

But this solution isn't as elegant. Any help would be appreciated.

The main complication is that the div tags "football" and "football2" might both be required for Cricket but only "football2" required for say Baseball.

Upvotes: 0

Views: 966

Answers (2)

Simon Arnold
Simon Arnold

Reputation: 16177

You can try this

function generateTask(){ $('#football, #football2').toggle();}

Or yan can add classes on every elements that should be affected by your dropdown: For example:

<div id="football" class="football">balls</div>
<div id="football2" class="football cricket">shorts</div>
<div id="cricket" class="cricket">stick</div>

And than target every element that's in link with your dropdown action.

Upvotes: 1

ShankarSangoli
ShankarSangoli

Reputation: 69915

If you can keep the value of the options as the ids of the divs then it will be much simpler. Something like this

Markup

<select name="something" id="something"> 
     <option value="football">Football</option> 
     <option value="cricket">Cricket</option> 
     <option value="baseball">Baseball</option> 
</select>
<div id="football" class="content">Football content</div>
<div id="cricket" class="content">Cricket content</div>
<div id="baseball" class="content">Baseball content</div>

JS

$("#something").change(function(){
    var id = "#"+this.value;
    //This will hide all the divs with class content but not the selected option
    $(".content").filter(":not("+id+")").hide();
    $(id).fadeToggle();//This will toggle div based on the selected option
});

Upvotes: 0

Related Questions