Reputation: 93
Long time browser, first time poster.
What I'd like to do is have a user select the number of weeks to display in a dropdown menu, and then reveal that many divs. Right now I have it setup where I can reveal one div or all, but I'd like to do it for the previous divs.
Right now I have:
<SELECT name="number_of_weeks" id="number_of_weeks">
<OPTION value = "week1">1</OPTION>
<OPTION value = "week2">2</OPTION>
<OPTION value = "week3">3</OPTION>
</SELECT>
<div id = "week1" class = "weekmenu">
Week 1 </br>
</div>
<div id = "week2" class = "weekmenu">
Week 2 </br>
</div>
<div id = "week3" class = "weekmenu">
Week 3 </br>
</div>
And for the javascript:
$(document).ready(function () {
$('.weekmenu').hide();
$('#week1').show();
$('#number_of_weeks').change(function () {
$('.weekmenu').hide();
$('#'+$(this).val()).show();
});
});
The output should be something like this: If week1 is selected only the week1 div is shown. If week 2 is selected, both the week1 and week2 divs are shown. If week 3 is selected the week1, week2, and week3 divs are shown.
I've been banging my head over this...I tried creating some nested divs but it didn't work out quite right. I also tried to give multiple divs their own classes, and then try to show those.
JSFiddle: http://jsfiddle.net/meRcr/21/
Any help is appreciated!
Upvotes: 4
Views: 919
Reputation: 13775
Use a cascading approach. Have a child-parent relationship through data-*
attributes. On each div, have its previous divs id in the attribute. data-parentid="2"
. Then you can just keep chaining your functionality until you get to a div with no parentid. You can change your layout anyway you choose and this relationship will be intact.
Upvotes: 0
Reputation: 123739
Try this:-
$('#' + $(this).val()).prevAll('.weekmenu').andSelf().show();
is the key.
.prevAll() will get you all the preceding siblings matching the selector .weekmenu
and then include itself too using andSelf()
to the collection.
$(document).ready(function () {
$('.weekmenu').hide();
$('#week1').show();
$('#number_of_weeks').change(function () {
$('.weekmenu').hide();
$('#' + $(this).val()).prevAll('.weekmenu').andSelf().show();
});
});
Upvotes: 2
Reputation: 772
Try something like this, I didn't test it but I think it works:)
$(document).ready(function () {
$('.weekmenu').hide();
$('#week1').show();
$('#number_of_weeks').change(function () {
$('.weekmenu').hide();
var weekNumbers = $(this).val();
for(var i = 1; i<= weekNumbers; i++) {
$('#week' + i).show();
}
});
});
Upvotes: 0
Reputation: 207901
Just change the last line of jQuery to:
$('#' + $(this).val()).prevUntil('select').addBack().show();
Full code:
$(document).ready(function () {
$('.weekmenu').hide();
$('#week1').show();
$('#number_of_weeks').change(function () {
$('.weekmenu').hide();
$('#' + $(this).val()).prevUntil('select').addBack().show();
});
});
Upvotes: 2