I have 5 divs for example
<div class="group" id="div1">Div1</div>
<div class="group" id="div2">Div2</div>
<div class="group" id="div3">Div3</div>
<div class="group" id="div4">Div4</div>
<div class="group" id="div5">Div5</div>
Then I have a select control:
<select id="mySelect">
<option value="1">1</option>
<option value="2" selected="selected">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
Then what I want to do: when “3” is selected in mySelect control, I want to display the first 3 divs, when “5” is selected, I want to display all divs. Additionally, the initial value of select is for example “2”, then when a page is load, I want to display first 2 divs. How can I achieve this?
Assuming the divs are in the order of the options, you could use the
:lt()selector jQuery offers:You could then add the following code to select the second one on load:
Here’s the edited fiddle. This has the (in my opinion pleasant) side-effect of not having to use ID’s at all.