Reputation: 1475
Hopefully this isn't a repeat question, but if it is, just post the link as your response.
I need to create a website with a select dropdown as the top with a few options, and several divs below with several links in them.
Depending on which option you select in the selectbox, the links that are labeled appropriately will get highlighted.
Here's the basic structure:
<select>
<option value="o1">Option 1</option>
<option value="o2">Option 2</option>
<option value="o3">Option 3</option>
<option value="o4">Option 4</option>
</select>
<div>
<a href="#" class="o1">Link A</a>
<a href="#" class="o2">Link B</a>
<a href="#" class="o3">Link C</a>
<a href="#" class="o4">Link D</a>
</div>
<div>
<a href="#" class="o1">Link A</a>
<a href="#" class="o2">Link B</a>
<a href="#" class="o3">Link C</a>
<a href="#" class="o4">Link D</a>
</div>
I know this process will include the .addClass() .removeClass() and .change(), I'm just not sure how to put it all together so that it works dynamically across all the divs.
Thanks in advance.
Upvotes: 2
Views: 3273
Reputation: 87083
$('select').on('change', function() { // binding change event for select
// fires when select box change
var mycls = this.value; // getting the value of select
// box after change
$('a:not(".'+ mycls +'")') // select <a> tag that has no
// class same as select box value
.removeClass('some_class'); // and remove highlight
// class form that <a>
$('a.' + mycls) // select the <a> with class
// same as select box value
.addClass('some_class'); // and adding highlight class
});
To make initially a link highlight just trigger an initial change
$('select').on('change', function() {
var mycls = this.value;
$('a:not(".'+ mycls +'")').removeClass('some_class');
$('a.' + mycls).addClass('some_class');
}).change(); // here the initial change event triggered
Upvotes: 1
Reputation: 290
Assuming you gave the select list an id e.g. selectid and you had a class called .highlight, you could do something like:
$('#selectid').change(function(){
$('*').removeClass('highlight');
$('.'+$(this).val()).addClass('highlight');
});
I've not tested the above but it should put you on the right track.
Upvotes: 0
Reputation: 12619
Seems like you already answered the question in the last sentence but here is that next step.
You have to add the .change() event handler to your select box.
$("select").change(function () {
});
Then when that even happens read the selected value and since you named them the same apply the style to that class.
$("select").change(function () {
$( "." + $(this).attr("value") ).css("background", "#ccc");
}
Upvotes: 0
Reputation: 10407
Link so:
$('select').on('change', function(){
var klass = this.value;
$('.highlight').removeClass('highlight');
$('a.'+klass).addClass('highlight');
});
Upvotes: 3