I’m making a mockup website the problem is I’m trying to filter my content using radiobuttons woth each has iets own value (manga,manwha
) and the content has class tags with different values (manga,manwha
) now I tried a few things in JavaScript but it only takes away the content when the radiobtn is checked but it need to do the opposite by only showing the contwnt that is checked
The code that a use is the following but with my own things added
function filterItems() {
// Get the selected radio button value
var selectedValue = document.querySelector('input[name="checkbox3"]:checked').value;
// Get all list items
var items = document.querySelectorAll('#manga, #manwga');
// Loop through each item and show/hide based on the selected radio button
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (item.getAttribute('data-type') === selectedValue || selectedValue === 'all') {
item.style.display = 'block';
} else {
item.style.display = 'none';
}
}
}
3
Answers
If your problem is that your code is hiding the content corresponding
radioButton
, you just have to make it so it hides all content NOT corresponding to theradioButton
. To do that, you only have to invert what theif
is doing fromto
If you need to invert the behavior you can change
if block
like this, and also you can to get rid of theelse block
.you actually don’t need this one
var item = items[i];
in the loop – it’s just memory spending.and a body of the loop will become so:
also let’s use
dataset
attribute correctly – dataset.typeBelow is an example that collects all the values from the checked inputs and puts them in an array on every change. It then loops over the elements you want to show or hide and checks for each element if the data type value corresponds with one of the values of the checked inputs.
Hide your elements by default and only show them by adding a class.