Reputation: 121
The education program I'm working on contains courses, and each course has at least one category and a course number. Sounds simple in theory, but when the program originally was written, it was not supposed to be possible for a course to have more than one category. The result is that the homepage shows the exact same courses listed several times, only with a different category tag(only seen in HTML). This is confusing for the user.
Instead of re-writing the whole structure, which will take me many days(I'm a pretty fresh developer), I want to use jQuery to just "hide" all the other divs.
HTML layout example:
<div id="cat_2_10" class="occurenceItem occurence_2" style="display: block;"></div>
<div id="cat_3_10" class="occurenceItem occurence_3" style="display: block;"></div>
<div id="cat_6_10" class="occurenceItem occurence_6" style="display: block;"></div>
In this example, there are 3 occurences of the same course(course number 10), in the categories 2, 3 and 6. These 3 divs contain a link to the exact same course, so there's no point to show all 3.
Is there a way I can use the jQuery selector to make sure only one of each course is visible? Remember, the category is irrelevant. Every '_' followed by a course number just needs to be unique. The moment one is taken, the others should have style="display: none".
Upvotes: 1
Views: 52
Reputation: 689
This seems to work.
for (var i = 0; i < 20; i++) {
$("[id^=cat_][id$=_" + i + "]").hide().first().show();
}
//[id^=cat_] -> id begins with cat_
//[id$=_ + i] -> id ends with _i
Note that here, I'm assuming the courses ids range from 0 to 20. I'm not sure how many courses there is but I figured doing a simple loop would be effective and simple enough.
If you don't want to loop over 'non-existing courses', you will have to build an array of course ids and then loop over them.
Upvotes: 0
Reputation: 1117
This might work:
var ids = [];
$('.occurenceItem').each(function() {
var id = $(this).attr('id').split('_').pop();
if (ids.indexOf(id) < 0) {
$(this).show();
ids.push(id);
} else {
$(this).hide();
}
});
Upvotes: 0
Reputation: 207901
I believe this will do what you want:
var courses = [];
$('.occurenceItem').filter(function() {
if ($.inArray(this.id.split('_').pop(), courses) === -1) {
courses.push(this.id.split('_').pop());
} else {return this}
}).hide()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="cat_2_10" class="occurenceItem occurence_2" style="display: block;">cat_2_10</div>
<div id="cat_3_10" class="occurenceItem occurence_3" style="display: block;">cat_3_10</div>
<div id="cat_6_10" class="occurenceItem occurence_6" style="display: block;">cat_6_10</div>
<div id="cat_7_4" class="occurenceItem occurence_2" style="display: block;">cat_7_4</div>
<div id="cat_8_4" class="occurenceItem occurence_3" style="display: block;">cat_8_4</div>
<div id="cat_9_4" class="occurenceItem occurence_6" style="display: block;">cat_9_4</div>
Upvotes: 2