Reputation: 435
I am running jQuery's .each
function on a button click that runs through three line items. When another object on the page is clicked one of the line items will receive a class of 'selected', it starts on the first line item as default.
I want to execute something when the data-index
of the li
is greater than 0 and that li
has the class name of selected
.
const $orderStatusButton = $('form#oar-widget-orders-and-returns-form button');
$orderStatusButton.on('click', function() {
$(".selectric-scroll ul li").each(function() {
var DataIndex = $(this).data('index');
console.log(DataIndex);
if ((DataIndex > 0) && ($(this).hasClass('selected'))) {
$('div#oar_select-error').css('display', 'none');
} else {
$('div#oar_select-error').css('display', 'block');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-index="0" class="selected"></li>
<li data-index="1" class=""></li>
<li data-index="2" class=""></li>
</ul>
Essentially, I want to hide a div when the line item with the data-index
of 1 or 2 has the class name of selected
and show it when the line item with the data-index
of 0 has the class name selected
and I'm not sure if I'm going about this correctly as it isn't working.
Upvotes: 0
Views: 47
Reputation: 884
Why not just use toggleClass("someclass")
and add CSS
li.someclass {
display:none;
OR
visibility:hidden;
};
Upvotes: 0
Reputation: 634
Since you are looping through all elements you'll always end up with the display value of the last iteration of the each function. What you should probably be doing is using the selected class on your jquery selector:
$(".selectric-scroll ul li.selected")
then you only have to process one element on the each function.
Upvotes: 3