开发者

jQuery hide elements depending on the dropdown selection option?

I am trying to hide a number of elements depending on the dropdown selection option number...Please have a look:

HTML:

<div class="box_1">some content</div>
<div class="box_2">some content</div>
<div class="box_3">some content</div>
<div class="box_4">some content</div>
<div class="box_5">some content</div>

<select id="select">
<option value="1">Show 1 boxes</option>
<option value="2">Show 2 boxes</option>
<option value="3">Show 3 boxes</option>
<option value="4">Show 4 boxes</option>
<option value="5">Show 5 boxes</option>
</select>

So far my JS looks like this:

jQuery("#select").change(function() {
     var currSelection = jQuery("option:select开发者_如何学Ced",this).val();

});

And I am not sure how to proceed from here...

So if 4 is selected for example, I want to hide the fifth box element and if 3 is selected, I want to hide the 4th and 5th box element...etc.. Thanks...


Try this

jQuery("#select").change(function() {
    $("div[class^='box_']").show().filter(":gt("+(parseInt($(this).val()) -1 )+")").hide();
}).change();

Working demo


This can be done very concisely using Array.slice (which works since jQuery objects are array-ish):

jQuery("#select").change(function() {
   $("div[class^='box']").hide().slice(0, $(this).val()).show();
}).change();

Try it out here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜