JQuery Select Multiple Dropdown Sections

Long-term browser, first time.

What I would like to do is tell the user the number of weeks to be displayed in the dropdown menu, and then show that many divs. Right now I have a setting where I can expand one div or all, but I would like to do this for previous divs.

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 javascript:

 $(document).ready(function () { $('.weekmenu').hide(); $('#week1').show(); $('#number_of_weeks').change(function () { $('.weekmenu').hide(); $('#'+$(this).val()).show(); }); }); 

The result should be something like this: If week1 is selected, only the div of week1 is displayed. If week 2 is selected, both weekly and weekly divs are displayed. If week 3 is selected, the weeks of the week, week2 and week are displayed.

I am busting my head over this ... I tried to create several nested divs, but this did not work out completely correctly. I also tried giving some divs to my classes, and then trying to show them.

JSFiddle: http://jsfiddle.net/meRcr/21/

Any help is appreciated!

+4
source share
4 answers

Just change the last jQuery line to:

  $('#' + $(this).val()).prevUntil('select').addBack().show(); 

JsFiddle example

Full code:

 $(document).ready(function () { $('.weekmenu').hide(); $('#week1').show(); $('#number_of_weeks').change(function () { $('.weekmenu').hide(); $('#' + $(this).val()).prevUntil('select').addBack().show(); }); }); 
+2
source

Try the following: -

$('#' + $(this).val()).prevAll('.weekmenu').andSelf().show(); is the key.

. prevAll () will provide you with all previous siblings matching the .weekmenu selector, and then include yourself with andSelf() in the collection as well.

 $(document).ready(function () { $('.weekmenu').hide(); $('#week1').show(); $('#number_of_weeks').change(function () { $('.weekmenu').hide(); $('#' + $(this).val()).prevAll('.weekmenu').andSelf().show(); }); }); 

Fiddle

+2
source

Try something like this, I have not tested 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(); } }); }); 
0
source

Use a cascading approach. You have a relationship between parents and parents using data-* attributes. Each div has its previous id div in the attribute. data-parentid="2" . Then you can just bind your functionality until you get to a div without a parent. You can change your layout one way or another as you choose, and this ratio will be intact.

0
source

Source: https://habr.com/ru/post/1481300/


All Articles