jquery - Show div with the same data-attribute as select option attribute -
i show divs set display none in css depending on multiple if statements. want use data-attributes , data value match data value of hidden div.
the options:
<select class="selectoptions" id="selectoptions1"> <option data-name="man"> man1 </option> <option data-name="woman"> woman </option> <option data-name="child"> child </option> </select> <select class="selectoptions" id="selectoptions2"> <option data-age="30"> man1 </option> <option data-age="25"> woman </option> <option data-age="10"> child </option> </select>
hidden divs:
<div class="datatest" data-age="25" data-name="man">hey man</div> <div class="datatest" data-age="20" data-name="woman">hello woman</div> <div class="datatest" data-age="10" data-name="child">hi child</div>
and js:
$('.selectoptions').on('change', function() { var agevalue = $('#selectoptions2 option:selected').data('age'); var namevalue = $('#selectoptions1 option:selected').data('name'); // alert(namevalue + ' ' + agevalue); $('.datatest').filter(function() { return this.dataset.name === namevalue || this.dataset.age === agevalue }).css("display", "block").siblings(".datatest").css("display", "none"); });
the values of data attributes on change found correctly alert showing them, can not use variables in conditions. welcome. thanks.
try utilizing .filter()
select .datatest
element, siblings()
hide selected .datatest
siblings
$('.selectoptions').on('change', function() { var agevalue = $(':selected', this).data('age'); var namevalue = $(':selected', this).data('name'); var filtered = agevalue || namevalue; alert(filtered); $('.datatest').filter(function() { var name = this.dataset.name, age = this.dataset.age; return name == filtered || age == filtered }).css("display", "block").siblings(".datatest").css("display", "none"); });
.datatest { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select class="selectoptions" id="selectoptions1"> <option data-name="man"> man1 </option> <option data-name="woman"> woman </option> <option data-name="child"> child </option> </select> <select class="selectoptions" id="selectoptions2"> <option data-age="30"> man1 </option> <option data-age="25"> woman </option> <option data-age="10"> child </option> </select> <div class="datatest" data-age="25" data-name="man">hey man</div> <div class="datatest" data-age="20" data-name="woman">hello woman</div> <div class="datatest" data-age="10" data-name="child">hi child</div>
Comments
Post a Comment