I have a drop down selection, once it select it will show the div where the value and class share the same name and hide all else.
How can I have it so before you select it'll show all and only hide after you select a option ?
EDIT I have updated the code snippet to run, have built in markup however on my local its php.
Revised question
how can I adjust my jQuery to show all, when none are selected and the selection is on default.
var $j = jQuery.noConflict();
$j(document).ready(function () {
$j("select").change(function () {
$j(this).find("option:selected").each(function () {
var optionValue = $j(this).attr("value");
if (optionValue) {
$j(".career_div").not("." optionValue).hide();
$j("." optionValue).show();
} else {
$j(".career_div").hide();
}
});
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value="all">Default</option>
<option value="one">Intelligence (2)</option>
<option value="two">Engineering (2)</option>
<option value="three">Marketing (0)</option>
</select>
<section >
<div >
<div >
<div >
<strong>Intelligence</strong>
</div>
<div >
<strong>Intelligence</strong>
</div>
<div >
<strong>Engineering</strong>
</div>
<div >
<strong>Engineering</strong>
</div>
</div>
</div>
</section>
CodePudding user response:
You can make a couple of changes:
use
$(this).val()
(this=select
) to get thevalue=
from the select option, no need to findoption:selected
and loop as.val()
does this for you.check for "all" then don't apply the filter
as noted in the comments, "one"/"two" were around the wrong way (no impact on functionality, just makes it look like it's wrong)
Updated snippet:
$(document).ready(function($) {
$("select").change(function() {
var opt = $(this).val();
if (opt === "all") {
$(".career_div").show();
} else {
$(".career_div").hide();
$("." opt).show();
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value="all">Default</option>
<option value="two">Engineering (2)</option>
<option value="one">Intelligence (2)</option>
<option value="three">Marketing (0)</option>
</select>
<section >
<div >
<div >
<div >
<strong>Intelligence</strong>
</div>
<div >
<strong>Intelligence</strong>
</div>
<div >
<strong>Engineering</strong>
</div>
<div >
<strong>Engineering</strong>
</div>
</div>
</div>
</section>