Search Filter with Javascript - javascript

I am trying to build a basic search filter where you search and a certain image appears on screen and I am trying to do this with javascript or simple jquery , I cannot seem to make the search work, and I am also wondering if it is possible to do a search based on a class name?
Here is my HTML code
<form onkeyup "function()" >
<input type="search" id = "myInput" placeholder="Search.." name="search" >
</form>
<ul id ="myUL">
<li class="SupernaturalCookbook"><img src="Images/SupernaturalCookbookCard.jpg" alt="SupernaturalCookbook"></li>
<li class="MarkOfAthena"><img src="Images/MarkOfAthenaCard.jpg" alt="MarkOfAthena"></li>
<li class="Instinct"><img src="Images/InstinctCard.jpg" alt="Instinct"></li>
<li class="CaminoIsland"><img src="Images/CaminoIslandCard.jpg" alt="caminoisland"></li>
<li class="TheLuckyOne"><img src="Images/TheLuckyOneCard.jpg" alt="theluckyone"></li>
<li class="TheWhistler"><img src="Images/TheWhistlerCard.jpg" alt="thewhistler"></li>
<li class="Greenlights"><img src="Images/GreenlightsCard.jpg" alt="greenlights"></li>
<li class="SeaOfMonsters"><img src="Images/SeaOfMonstersCard.jpg" alt="seaofmonsters"></li>
<li class="SerpentShadows"><img src="Images/SerpentShadowsCard.jpg" alt="serpentshadows"></li>
<li class="FromCrookToCook"><img src="Images/FromCrookToCookCard.jpg" alt="fromcrooktocook"></li>
</ul>
Here is my Javascript code:
var input = document.getElementById('myInput');
input.onkeyup = function () {
var filter = myInput.value.toUpperCase();
var lis = document.getElementsByTagName('li');
for (var i = 0; i < lis.length; i++) {
var name = lis[i].getElementsByClassName('class')[0].innerHTML;
if (name.toUpperCase().indexOf(filter) == 0)
lis[i].style.display = 'list-item';
else
lis[i].style.display = 'none';
}

In addition to what others added, please keep in mind that onkeyup only triggers when someone releases a key. However, there are other ways to change the input of an input field such as cut, paste, clear, etc. To make sure you have covered all the aspects, you can wrap your code in a named function and bind it to the following events
function search_images(){
///code goes here
}
input.onkeyup = search_images
input.onchange = search_images
input.onpaste = search_images
input.oncut = search_images
input.oninput = search_images
Also, be sure to RESET the filter if the input is empty. An alternative solution is as follows:-
function search_images() {
let filter = this.value.toUpperCase();
let lis = Array.from(document.getElementsByTagName('li'));
if (filter.length > 0) {
lis.forEach(li => {
if (Array.from(li.classList).join(" ").toUpperCase().indexOf(filter) >= 0) {
li.style.display = "list-item"
} else {
li.style.display = "none"
}
})
} else {
lis.forEach(li => li.style.display = "list-item")
}
}
const input = document.getElementById('myInput');
input.onkeyup = search_images
input.onchange = search_images
input.onpaste = search_images
input.oncut = search_images
input.oninput = search_images
<form>
<input type="search" id="myInput" placeholder="Search.." name="search">
</form>
<ul id="myUL">
<li class="SupernaturalCookbook">
<img src="Images/SupernaturalCookbookCard.jpg" alt="SupernaturalCookbook">
</li>
<li class="MarkOfAthena">
<img src="Images/MarkOfAthenaCard.jpg" alt="MarkOfAthena">
</li>
<li class="Instinct">
<img src="Images/InstinctCard.jpg" alt="Instinct">
</li>
<li class="CaminoIsland">
<img src="Images/CaminoIslandCard.jpg" alt="caminoisland">
</li>
<li class="TheLuckyOne">
<img src="Images/TheLuckyOneCard.jpg" alt="theluckyone">
</li>
<li class="TheWhistler">
<img src="Images/TheWhistlerCard.jpg" alt="thewhistler">
</li>
<li class="Greenlights">
<img src="Images/GreenlightsCard.jpg" alt="greenlights">
</li>
<li class="SeaOfMonsters">
<img src="Images/SeaOfMonstersCard.jpg" alt="seaofmonsters">
</li>
<li class="SerpentShadows">
<img src="Images/SerpentShadowsCard.jpg" alt="serpentshadows">
</li>
<li class="FromCrookToCook">
<img src="Images/FromCrookToCookCard.jpg" alt="fromcrooktocook">
</li>
</ul>

If you want to filter by class name, replace this line ...
var name = lis[i].getElementsByClassName('class')[0].innerHTML;
... with this:
var name = lis[i].className;

var input = document.getElementById('myInput');
input.onkeyup = function () {
var filter = input.value.toUpperCase();
var lis = document.getElementsByTagName('li');
for (var i = 0; i < lis.length; i++) {
var name = lis[i].className; // takes the classname
if (name.toUpperCase().indexOf(filter) >= 0) //Changed this part
lis[i].style.display = 'list-item';
else
lis[i].style.display = 'none';
}
}
indexOf method returns -1 if not found, else it will be greater than or equal than 0.

Related

This code is working but after working Why this code is showing error

here is the html part ..
var removeButton = document.getElementById("remove");
removeButton.addEventListener("click", removeItem);
function removeItem() {
var list = document.getElementById("list");
var listItems = list.getElementsByTagName("li");
var last = listItems[listItems.length - 1];
list.removeChild(last);
if (last == listItems.length - 1) {
document.getElementById("remove").disabled = true;
}
}
<ul id="list">
<li class="abc">cold cereal</li>
<li class="abc">Ice cream</li>
<li class="abc">Honey</li>
<li class="abc">Olive Oil</li>
</ul>
<button id="btn" onclick="myfun()">add item</button>
<button id="remove">remove item</button>
clicked on the remove button and its removing the items from the list after all the items are deleted from the list its showing the error .
when i run this code every thing is working fine but when all the items are deleted from the list after deleting all the list items from the list when i press the button once more it shows the error
this way
const
removeButton = document.getElementById('remove')
, list = document.getElementById('list')
;
removeButton.addEventListener("click", removeItem);
function removeItem()
{
let
listItems = list.querySelectorAll('li')
, lastRef = listItems.length - 1
;
list.removeChild(listItems[lastRef] );
if (lastRef === 0) {
removeButton.disabled = true;
}
}
<ul id="list">
<li class="abc">cold cereal</li>
<li class="abc">Ice cream</li>
<li class="abc">Honey</li>
<li class="abc">Olive Oil</li>
</ul>
<button id="btn" onclick="myfun()">add item</button>
<button id="remove">remove last item</button>
i don't know why you used this
if( last == listItem.length - 1)
{
document.getElementById('remove').disable = true;
}
try this
if(listItem.length - 1 === 0){
document.getElementById("remove").disabled = true;
}
}
When your all nodes are deleted then you can't perform delete operation you will have to apply a condition to overcome this
Replace your removeItem function code with the given below-
function removeItem() {
var list = document.getElementById("list");
var listItems = list.getElementsByTagName("li");
if (listItems.length > 0) {
var last = listItems[listItems.length - 1];
list.removeChild(last);
}
else{
alert("can't delete")
}
}

jQuery get many objects with same class and switch between them

Does anyone know how to grab many objects with same class in jQuery and then show previous object with same class by clicking prev button and next one by next btn? I'm just starting with programming and try to write recipies store and I stucked on that, I can grab value of element I click on but don't know how to switch between them using buttons
<div>
<button class="prev"></button>
<button class="next"></button>
<p class="showRecipies"></p>
<ul>
<li class="recipies">Drinks</li>
<li class="recipies">Vegetables</li>
<li class="recipies">Meet</li>
<li class="recipies">Fruits</li>
<li class="recipies">Others</li>
</ul>
</div>
JQuery to grab value of recipie I clicked on
$(".recipies").on("click", function () {
var recipieValue = $(this).text();
var showRecipies = document.querySelector(".showRecipies");
showRecipies.innerHTML = recipieValue;
})
UPDATED:
it works but let me ask one more question:) and thank you for your help so far! I decided to a bit improve my code to make it easier to style and update and I decided that every recipie will be separate ul, to make it easier to read etc
<div>
<button class="prev"></button>
<button class="next"></button>
<p class="showRecipies"></p>
<ul class="listOfRecipies">
<li>
<ul class="particularRecipie">
<li class "timeOfPreparation>3:20</li>
<li class="recipies">Drinks</li>
</ul>
</li>
<li class "timeOfPreparation>3:20</li>
<li class="recipies">Vegetables</li>
<li>
<ul class="particularRecipie">
<li class "timeOfPreparation>3:20</li>
<li class="recipies">Meet</li>
</ul>
</li>
<li>
<ul class="particularRecipie">
<li class "timeOfPreparation>3:20</li>
<li class="recipies">Fruits</li>
</ul>
</li>
<li>
<ul class="particularRecipie">
<li class "timeOfPreparation>3:20</li>
<li class="recipies">Others</li>
</ul>
</li>
</div>
In this case I should just go higher through parent() property right? Like:
$(".recipies").on("click", function() {
$(".recipies.active").add($(this)).toggleClass("active");
var recipieValue = $(this).text();
var showRecipies = document.querySelector(".showRecipies");
showRecipies.innerHTML = recipieValue;
});
$(".next").click(function() {
var isLast = $(".recipies.active").is(":last-child");
var $this = $(".recipies.active") || $(".recipies:first");
if(isLast){
$this.parent().parent().find(".recipies:first").trigger("click");
} else {
$this.next().trigger("click");
}
});
$(".prev").click(function() {
var isFirst = $(".recipies.active").is(":first-child");
var $this = $(".recipies.active") || $(".recipies:first");
if(isFirst){
$this.parent().parent().find(".recipies:last").trigger("click");
} else {
$this.prev().trigger("click");
}
});
You can use this code:
$(".next").click(function() {
var isLast = $(".recipies.active").is(":last-child");
if(isLast){
$(this).parent().find(".recipies:first").trigger("click");
} else {
$(".recipies.active").next().trigger("click");
}
});
$(".prev").click(function() {
var isFirst = $(".recipies.active").is(":first-child");
if(isFirst){
$(this).parent().find(".recipies:last").trigger("click");
} else {
$(".recipies.active").prev().trigger("click");
}
});
I've added $(".recipies.active").add($(this)).toggleClass("active"); to your .recipies click function, so we know what li is active/has been clicked
Demo
$(".recipies").on("click", function() {
$(".recipies.active").add($(this)).toggleClass("active");
var recipieValue = $(this).text();
var showRecipies = document.querySelector(".showRecipies");
showRecipies.innerHTML = recipieValue;
});
$(".next").click(function() {
var isLast = $(".recipies.active").is(":last-child");
var $this = $(".recipies.active") || $(".recipies:first");
if(isLast){
$this.parent().find(".recipies:first").trigger("click");
} else {
$this.next().trigger("click");
}
});
$(".prev").click(function() {
var isFirst = $(".recipies.active").is(":first-child");
var $this = $(".recipies.active") || $(".recipies:first");
if(isFirst){
$this.parent().find(".recipies:last").trigger("click");
} else {
$this.prev().trigger("click");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button class="prev">prev</button>
<button class="next">next</button>
<p class="showRecipies"></p>
<ul>
<li class="recipies">Drinks</li>
<li class="recipies">Vegetables</li>
<li class="recipies">Meet</li>
<li class="recipies">Fruits</li>
<li class="recipies">Others</li>
</ul>
</div>
You can use the prev() and next() to cycle through the available recipies:
var rec = $('.recipies:first');
$('.showRecipies').html(rec.html());
$('.prev').click(function() {
rec = rec.prev('.recipies');
if (!rec.length) {
rec = $('.recipies:last');
}
$('.showRecipies').html(rec.html());
});
$('.next').click(function() {
rec = rec.next('.recipies');
if (!rec.length) {
rec = $('.recipies:first');
}
$('.showRecipies').html(rec.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button class="prev">prev</button>
<button class="next">next</button>
<p class="showRecipies"></p>
<ul>
<li class="recipies">Drinks</li>
<li class="recipies">Vegetables</li>
<li class="recipies">Meet</li>
<li class="recipies">Fruits</li>
<li class="recipies">Others</li>
</ul>
</div>
Next button:
$(".next").click(function () {
let currentRecipies = $('.recipies.current');
let currentRecipiesValue = $('.recipies.current').text();
let currentRecipiesIndex = $('.recipies.current').index();
let nextRecipiesIndex = currentRecipiesIndex + 1;
let nextRecipies = $('.recipies').eq(nextRecipiesIndex);
currentRecipies.removeClass('current');
let showRecipies = document.querySelector(".showRecipies");
if (nextRecipiesIndex == ($('.recipies:last').index()+1)) {
$('.recipies').eq(0).addClass('current');
showRecipies.innerHTML = currentRecipiesValue
} else {
nextRecipies.addClass('current');
showRecipies.innerHTML = currentRecipiesValue
}
})
Prev:
$(".prev").click(function () {
let currentRecipies = $('.recipies.current');
let currentRecipiesValue = $('.recipies.current').text();
let currentRecipiesIndex = $('.recipies.current').index();
let nextRecipiesIndex = currentRecipiesIndex - 1;
let nextRecipies = $('.recipies').eq(nextRecipiesIndex);
currentRecipies.removeClass('current');
let showRecipies = document.querySelector(".showRecipies");
if (nextRecipiesIndex == ($('.recipies:first').index() - 1)) {
$('.recipies').eq(4).addClass('current');
showRecipies.innerHTML = currentRecipiesValue
} else {
nextRecipies.addClass('current');
showRecipies.innerHTML = currentRecipiesValue
}
})

How to bold searched content using only javascript?

I'm trying to make an auto suggest search using javascript. All things are working fine, now i wanted to make searched text bold in the list.
Is this possible when user search something then only search text become bold in the result list. For example if i search one then one will be bold in the list.
var inputId = 'filter-search';
var itemsData = 'filter-value';
var displaySet = false;
var displayArr = [];
function getDisplayType(element) {
var elementStyle = element.currentStyle || window.getComputedStyle(element, "");
return elementStyle.display;
}
document.getElementById(inputId).onkeyup = function() {
var searchVal = this.value.toLowerCase();
var filterItems = document.querySelectorAll('[' + itemsData + ']');
for(var i = 0; i < filterItems.length; i++) {
if (!displaySet) {
displayArr.push(getDisplayType(filterItems[i]));
}
filterItems[i].style.display = 'none';
if(filterItems[i].getAttribute('filter-value').toUpperCase().indexOf(searchVal.toUpperCase()) >= 0) {
filterItems[i].style.display = displayArr[i];
}
}
displaySet = true;
}
<input type="text" id="filter-search" />
<ul>
<li filter-value="One Is">One Is (Uppercase)</li>
<li filter-value="one is">one is (Lowercase)</li>
<li filter-value="two">Two</li>
<li filter-value="three">Three</li>
<li filter-value="four">Four</li>
<li filter-value="five" >Five</li>
<li filter-value="six">Six</li>
<li filter-value="seven">Seven</li>
<li filter-value="eight">Eight</li>
<li filter-value="nine">Nine</li>
<li filter-value="ten" >Ten</li>
</ul>
I have done this via using below code
var textcontent = filterItems[i].textContent;
var replacedval = "<strong>"+currval+"</strong>"
var finalval = textcontent.replace(currval, replacedval);
filterItems[i].innerHTML = finalval;
filterItems[i].style.display = 'none';
Here is working JSFiddle
https://jsfiddle.net/ku5zv3dz/
It's not possible to change the style of only a part of a text contained within an element.
To do what you ask, you have to create an additional element (say, a <span> element) which will contain only the text you want to make bold, and append it. Then, you have to remove the same text from the original element.
For example
<li filter-value="One Is">
<span class="bold">One</span> Is (Uppercase)
</li>
Since you already know which part of the text has been searched, it should be trivial to do this using String.replace() and DOM manipulation methods like document.createElement and document.appendChild.
Here's what I got. I'm a little confused with your toLowerCase and toUpperCase code, but for the most part this works. Type in 'o', or 'u', or any of the above to test. It'll bold just what you typed in (in lowercase, since that's what your code does..)
var inputId = 'filter-search';
var itemsData = 'filter-value';
var displaySet = false;
var displayArr = [];
function getDisplayType(element) {
var elementStyle = element.currentStyle || window.getComputedStyle(element, "");
return elementStyle.display;
}
document.getElementById(inputId).onkeyup = function() {
var searchVal = this.value.toLowerCase();
var filterItems = document.querySelectorAll('[' + itemsData + ']');
for (var i = 0; i < filterItems.length; i++) {
var elem = filterItems[i]; // assign it to a variable so that i don't have to constantly say filterItems[i]
if (!displaySet) {
displayArr.push(getDisplayType(elem));
}
elem.style.display = 'none';
elem.innerHTML = elem.innerHTML.replace(/<b>/g, '').replace(/<\/b>/g, ''); // strip away all previous bold
if (elem.getAttribute('filter-value').toUpperCase().indexOf(searchVal.toUpperCase()) >= 0) {
elem.style.display = displayArr[i];
if (searchVal.length > 0) {
elem.innerHTML = elem.innerHTML.replace(new RegExp(searchVal, 'g'), '<b>' + searchVal + '</b>'); // replace search with bold
}
}
}
displaySet = true;
}
.
<input type="text" id="filter-search" />
<ul>
<li filter-value="One Is">One Is (Uppercase)</li>
<li filter-value="one is">one is (Lowercase)</li>
<li filter-value="two">Two</li>
<li filter-value="three">Three</li>
<li filter-value="four">Four</li>
<li filter-value="five" >Five</li>
<li filter-value="six">Six</li>
<li filter-value="seven">Seven</li>
<li filter-value="eight">Eight</li>
<li filter-value="nine">Nine</li>
<li filter-value="ten" >Ten</li>
</ul>
JSFiddle: https://jsfiddle.net/x5amcaqr/

Auto calculate sum of data attribute in pure JavaScript

I have tried for so long now to auto calculate the sum of data attribute when adding/removing something to a shopping basket from and calculate the total of data attribute in pure JavaScript no Jquery without being able to fix it! I am pretty new to JavaScript...
Here is my code:
HTML:
//The shopping basket section
<div id="basket">Shopping Basket</div>
<ul class="cart" id="cart_id">
</ul>
<form>
<br>Total Price:
<input type="text" name="totalPrice" id="totalPrice" value="€ 0" disabled>
</form>
<div>
//The category selection section
<ul class="products" id="product_id">
<li class="cat" id="cat_id" name="data" data-title="iPad" data-price="299">iPad (€299)<img class="plusicon" src="plusicon.jpg" alt="plusicon"/></li>
<li class="cat" id="cat_id" name="data" data-title="iPad Air" data-price="399">Ipad Air (€399)<img class="plusicon" src="plusicon.jpg" alt="plusicon"/></li>
<li class="cat" id="cat_id" name="data" data-title="Sony Xperia Z2" data-price="399">Sony Xperia Z2 (€399)<img class="plusicon" src="plusicon.jpg" alt="plusicon"/></li>
<li class="cat" id="cat_id" name="data" data-title="Samsung Galaxy Tab 10,1" data-price="349">Samsung Galaxy Tab 10,1 (€349)<img class="plusicon" src="plusicon.jpg" alt="plusicon"/></li>
</ul>
JS :
function init(){
plus = [].slice.call(document.querySelectorAll(".plusicon"), 0);
for (var i = 0; i < plus.length; i++) {
plus[i].addEventListener("click", addToBasasket, false);
}
}
function addToBasket (e) {
e.stopPropagation();
var ele = info[plus.indexOf(this)];
var title = ele.getAttribute("data-title");
var price = parseInt(ele.getAttribute("data-price"));
var ul = document.getElementById("cart_id");
var li = document.createElement("li");
var remove = document.createElement("img");
remove.className = "removeicon";
remove.src = "removeicon.jpg";
remove.addEventListener("click", removeThingFromList, false);
li.appendChild(remove);
li.appendChild(document.createTextNode(title+" (\u20AC"+price+")"));
ul.appendChild(li);
//So when you press "plusicon" it adds to shopping basket and when you press "removeicon" it deletes from the basket!
//Here below is my problem, I have tried for so long but I cant get to work
//to show the total price when adding and removing li to basket!
var total = 0;
listItem = ele.getAttribute("data-price");
for (var i=0; i < listItem.length; i++)
{
total += parseInt(ele.getAttribute("data-price"));
}
document.querySelector("#totalPrice").value = total;
//I have tried so many different ways but can't get it to work the total of attribute("data-price")!
//This functions below works and removes the current li
function removeThingFromList(e){
this.parentNode.parentNode.removeChild(this.parentNode);
}
}
I hope someone can help! Thanks in advance!
You have to store the price in some attribute in new items (li) added to your basket :
li.appendChild(remove);
//Storing price in data-price attribute
li.setAttribute("data-price", price);
li.appendChild(document.createTextNode(title+" (\u20AC"+price+")"));
ul.appendChild(li);
And after that you can get this attribute and calculate the total :
var total = 0;
var listItem = document.getElementById("cart_id").getElementsByTagName("li");
for (var i=0; i < listItem.length; i++)
{
total += parseInt(listItem[i].getAttribute("data-price"));
}
<ul>
<li class="cart_item" data-prize="12.6" data-id="5">Hello €12.6</li>
<li class="cart_item" data-prize="4.25" data-id="8">World €4.25</li>
<li class="cart_item" data-prize="13.8" data-id="9">Foo €13.8</li>
<li class="cart_item" data-prize="6.3" data-id="12">Bar €6.3</li>
</ul>
<input type="button" value="TOTAL" onclick="calculateTotal();">
<div id="messages"></div>
<script>
function data(elm, key) {
for(var i in elm.attributes) {
if ( elm.attributes[i].name.substr(0, 5) === 'data-' ) { // checks if the 5 first letters of the attribute are 'data-'
// it's a data- attribute. Now let's see if it's the right one
if ( elm.attributes[i].name.substr(5) === key) { // checks if the letters, next to the 5 first letters, correspond with the key we need
return elm.attributes[i].value;
}
}
}
return '';
}
function calculateTotal() {
document.getElementById("messages").innerHTML = '';
var items = document.getElementsByClassName("cart_item");
var sum=0;
for (var i in items) {
var prize = Number( data(items[i], 'prize') ); // without the Number(), it's seen as text
sum += prize;
if(prize) { // else it also shows blank lines
document.getElementById("messages").innerHTML += prize + '<br>';
}
}
document.getElementById("messages").innerHTML += '+ -----<br>' + sum;
}
</script>

Apply multiple filter categories to a list of <li>(s) with javascript

I have this fiddle and I want to know how I can implement filtering function based on two categories. when someone click the filter, it should get the values from both the current filters selection, hide the list and show only the filter result. Any idea on how to implement this step? any help would be appreciated!!
<ul style='list-style-type: none;' class="filter1">
<li><span class="filtercat1">red</span>
</li>
<li><span class="filtercat1">blue</span>
</li>
<li><span class="filtercat1">yellow</span>
</li>
<li><span class="filtercat1">all</span>
</li>
</ul> <span id="filterbutton1">
« Previous
Next »
</span>
<ul style='list-style-type: none;' class="filter2">
<li><span class="filtercat2">orange</span>
</li>
<li><span class="filtercat2">apple</span>
</li>
<li><span class="filtercat2">papaya</span>
</li>
<li><span class="filtercat2">all</span>
</li>
</ul> <span id="filterbutton2">
« Previous
Next »
</span>
<ul id='list'>
<li class="">red orange</li>
<li class="">red apple</li>
<li class="">red papaya</li>
<li class="">blue orange</li>
<li class="">blue apple</li>
<li class="">blue papaya</li>
<li class="">yellow orange</li>
<li class="">yellow apple</li>
<li class="">yellow papaya</li>
</ul>
<span id="filterbutton">
filter
<span id="resetbutton">
reset
$(function () {
var all = $('.filtercat1').addClass("passiv");
var i = -1;
$('#prev' ).click(function () {
ctrlbutton(i = !i ? all.length - 1 : --i);
});
$('#next').click(function () {
ctrlbutton(i = ++i % all.length);
}).click();
function ctrlbutton(ele) {
all.removeClass("active").addClass("passiv");
all.eq(ele).removeClass("passiv").addClass("active");
}
})
$(function () {
var all = $('.filtercat2').addClass("passiv");
var i = -1;
$('#prev2').click(function () {
ctrlbutton(i = !i ? all.length - 1 : --i);
});
$('#next2').click(function () {
ctrlbutton(i = ++i % all.length);
}).click();
function ctrlbutton(ele) {
all.removeClass("active").addClass("passiv");
all.eq(ele).removeClass("passiv").addClass("active");
}
})
fiddle: http://jsfiddle.net/BlacBunny/5tfcuy1w/
Use this code
$("#list").find("li").each(function(){
this.className = "all "+this.innerHTML;
});
$("#filter").click(function(){
var class1 = $(".filter1").find(".active").text();
var class2 = $(".filter2").find(".active").text();
$("#list").find("li").addClass("passiv").end().find("."+class1+"."+class2)
.removeClass("passiv").addClass("active");
});
$("#reset").click(function(){
$("#list").find("li").addClass("active").removeClass("passiv");
});
I have not optimized this code. You are using dom ready function two times which is actually not required.
You can see the fiddle here
See Fiddle
This function will be called every time the filters are modified. The values of filter1 and filter2 must be modified per click to the filter buttons.
var filter1 = 'red'; // initial value of filter1
var filter2 = 'orange'; // initial value of filter2
function filterList() {
var list = $('#list li');
list.each(function(index, item) {
var itemContents = $(item).text();
if (itemContents.indexOf(filter1) >= 0 && itemContents.indexOf(filter2) >= 0) {
$(item).show();
} else {
console.log('hide ' + itemContents);
}
});
}
Fiddle
$("#filter").click(function() {
var filterCat1 = $(".filter1 .active").text();
var filterCat2 = $(".filter2 .active").text();
$("#list li").each( function( index, element ){
var text = $(element).text();
if((text.indexOf(filterCat1) < 0 && filterCat1 != "all")
|| (text.indexOf(filterCat2) < 0 && filterCat2 != "all"))
$(element).removeClass("active").addClass("passiv");
else
$(element).removeClass("passiv").addClass("active");
});
});
Try the contains selector
$('#filter').click(function() {
$("#list li").addClass("passiv");
var filter1 = $(".filter1 span.active").text();
var filter2 = $(".filter2 span.active").text();
var filter= (filter1 == "all" ? "" : filter1) + " " + (filter2 == "all" ? "" : filter2);
$('#list li:contains("' + filter + '")').removeClass("passiv");
});
http://jsfiddle.net/5tfcuy1w/10/

Categories