2

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:selected",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...

2 Answers 2

1

Try this

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

Working demo

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks-on my side it threw an error..."uncaught exception class^=.."
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.