I have created 4 buttons in my HTML file.
I have an object in my JavaScript file named products created using curly brackets {}.
Within this object, I have an Array named data created using square brackets [].
Within this Array, I have a number of different objects created using curly brackets {}.
Each of the objects within the Array are displayed correctly. I now want to create a filter, which will only show certain objects within the Array, depending on which button is pressed.
In my HTML file, I have this code:
<div id="buttons">
<button id="all" class="button-value" onclick="filterProduct('all')">All</button>
<button id="product1" class="button-value" onclick="filterProduct('product1')">Product 1</button>
<button id="product2" class="button-value" onclick="filterProduct('product2')">Product 2</button>
<button id="product3" class="button-value" onclick="filterProduct('product3')">product3</button>
</div>
In my CSS file, I have this code:
.hide {
display: none;
}
The object I have created in JavaScript:
let products = {
data: [
{
productName: "Item 1",
category: "product1",
price: "30",
image: "image-of-the-product-1.jpg",
},
{
productName: "Item 2",
category: "product2",
price: "49",
image: "image-of-the-product-2.jpg",
},
{
productName: "Item 3",
category: "product3",
price: "99",
image: "image-of-the-product-3.jpg",
},
]
}
The filterProduct function in JavaScript:
// Parameter passed from button (Parameter same as category)
function filterProduct(value) {
// Select all elements
let elements = document.querySelectorAll(".card");
// Loop through the elements
elements.forEach((element) => {
// Display all cards on all button click
if (value == "all") {
element.classList.remove("hide");
} else {
// Check if element contains category class
if (element.classList.contains(value)) {
// Display elements based on category
element.classList.remove("hide");
} else {
// Hide other elements
element.classList.add("hide");
}
}
});
}
If the user clicks on the button with the product1 filter, only products with the category of product1 should show up. If the user clicks on a button with the product2 filter, only products with the category of product2 should show up. If the user clicks on the button with the product3 filter, only products with the category of product3 should show up. If the user clicks on the All button, all the products should be shown.
Here you can find Working demo
DEMO
I have added my own card as of now but you can change this acording your necessity.
let products = {
data: [{
productName: "Item 1",
category: "product1",
price: "30",
image: "https://via.placeholder.com/200x200",
},
{
productName: "Item 2",
category: "product2",
price: "49",
image: "https://via.placeholder.com/400x400",
},
{
productName: "Item 3",
category: "product3",
price: "99",
image: "https://via.placeholder.com/350x150",
},
{
productName: "Item 3",
category: "all",
price: "99",
image: "https://via.placeholder.com/200x100",
},
]
}
function filterAllProduct(value) {
console.clear();
let a = [];
var container = document.getElementById("displayImage");
let list = container.classList;
list.add("uicomponent-panel-controls-container");
for (var i = 0; i < products.data.length; i++) {
container.innerHTML += '<img src=' + products.data[i]['image'] + ' />';
}
}
function filterProduct(value) {
console.clear();
var newArray = products.data.filter(function(item) {
return item.category == value;
})[0];
var html = [
'<div class="uicomponent-panel-controls-container">',
'<img src=' + newArray.image + '>',
'</div>'
].join('\n');
document.getElementById("displayImage").innerHTML = html;
}
.hide {
display: none;
}
<div id="buttons">
<button id="all" class="button-value" onclick="filterAllProduct('all')">All</button>
<button id="product1" class="button-value" onclick="filterProduct('product1')">Product 1</button>
<button id="product2" class="button-value" onclick="filterProduct('product2')">Product 2</button>
<button id="product3" class="button-value" onclick="filterProduct('product3')">product3</button>
</div>
<div id="displayImage"></div>
let products = {
data: [{
productName: "Item 1",
category: "product1",
price: "30",
image: "https://via.placeholder.com/200x200",
},
{
productName: "Item 2",
category: "product2",
price: "49",
image: "https://via.placeholder.com/200x100",
},
{
productName: "Item 3",
category: "product3",
price: "99",
image: "https://via.placeholder.com/200x100",
},
{
productName: "All",
category: "all",
price: "100",
image: "https://via.placeholder.com/400x400",
},
]
}
var getSelectedValue = '';
var html = '';
function filterProduct(value) {
getSelectedValue = value;
var image1 = '';
switch (value) {
case 'all':
image1 = 'https://via.placeholder.com/200x100';
html = [
'<div class="uicomponent-panel-controls-container">',
'<img src=' + products.data[0]['image'] + '> <span>' + products.data[0]['price'] + '</span> \n',
'<img src=' + products.data[1]['image'] + '> <span>' + products.data[1]['price'] + '</span> \n',
'<img src=' + products.data[2]['image'] + '> <span>' + products.data[2]['price'] + '</span> \n',
'</div>'
].join('\n');
break;
case 'product1':
image1 = 'https://via.placeholder.com/200x200';
html = [
'<div class="uicomponent-panel-controls-container">',
'<img src=' + image1 + '> ',
'</div>'
].join('\n');
break;
case 'product2':
image1 = 'https://via.placeholder.com/400x400';
html = [
'<div class="uicomponent-panel-controls-container">',
'<img src=' + image1 + '>',
'</div>'
].join('\n');
break;
case 'product3':
image1 = 'https://via.placeholder.com/350x150';
html = [
'<div class="uicomponent-panel-controls-container">',
'<img src=' + image1 + '>',
'</div>'
].join('\n');
break;
default:
// default code block
}
if (getSelectedValue == 'all') {
}
document.getElementById("displayImage").innerHTML = html;
}
.hide {
display: none;
}
<div id="buttons">
<button id="all" class="button-value" onclick="filterProduct('all')">All</button>
<button id="product1" class="button-value" onclick="filterProduct('product1')">Product 1</button>
<button id="product2" class="button-value" onclick="filterProduct('product2')">Product 2</button>
<button id="product3" class="button-value" onclick="filterProduct('product3')">product3</button>
</div>
<div id="displayImage"></div>
If Data is static then you can use switch case this is how you can display image according button click
If Data is dynamic and you are not able to map that you can use filter to map that data
Related
I am trying to create a page to add a new user when click into a value on menu bar like an Add option that allows users to input a name, an office number, and a phone number
Here is my code:
let menu = ["View", "Add", "Verify", "Update", "Delete"];
let list = document.getElementById("menuList");
menu.forEach((item) => {
let li = document.createElement("li");
li.innerText = item;
list.appendChild(li);
});
let users = [
{ name: "Jan", id: "1", number: "111-111-111" },
{ name: "Juan", id: "2", number: "222-222-222" },
{ name: "Margie", id: "3", number: "333-333-333" },
{ name: "Sara", id: "4", number: "444-444-444" },
{ name: "Tyrell", id: "5", number: "555-555-555" },
];
var div = "<div class='infor'>";
for (var i = 0; i < users.length; i++) {
div += "<div class='user-informations'>";
div += "<p>" + users[i].name + "</p>";
div += "<p>" + users[i].id + "</p>";
div += "<p>" + users[i].number + "</p>";
div += "</div>";
}
div += "</div>";
document.getElementById("usersList").innerHTML = div;
<div class="contact-container">
<div class="navbar">
<ul id="menuList">
<img src="https://img.icons8.com/ios-filled/50/000000/contact-card.png"/>
</ul>
</div>
<div class="users" id="usersList">
</div>
</div>
my project:
Paying no attention to style or good software engineering practices:
let usersList = document.getElementById("usersList"),
addPage = document.getElementById("addPage");
const users = [
{ name: "Jan", id: "1", number: "111-111-111" },
{ name: "Juan", id: "2", number: "222-222-222" },
{ name: "Margie", id: "3", number: "333-333-333" },
{ name: "Sara", id: "4", number: "444-444-444" },
{ name: "Tyrell", id: "5", number: "555-555-555" },
];
function showUsers() {
usersList.innerHTML = "";
usersList.style.display = "inline";
addPage.style.display = "none";
users.forEach(u => {
const newUser = document.createElement("p");
newUser.innerHTML = `${u.id} ${u.name}<br/>${u.number}`;
usersList.appendChild(newUser);
})
}
function addOn() {
usersList.style.display = "none";
addPage.style.display = "inline";
}
function addUser() {
const id = document.getElementById("id").value;
const name = document.getElementById("name").value;
const number = document.getElementById("number").value;
users.unshift({ name: name, id: id, number: number});
showUsers();
}
showUsers();
.navbar { vertical-align: top; padding-right: 1rem; border-right:solid 1px red }
<div class="contact-container">
<table>
<tr>
<td class="navbar">
<ul id="menuList" style="cursor:pointer">
<img src="https://img.icons8.com/ios-filled/50/000000/contact-card.png" />
<li onclick="showUsers()">View</li>
<li onclick="addOn()">Add</li>
<li>...</li>
</ul>
</td>
<td>
<div class="users" id="usersList"></div>
<div id="addPage" style="display:none">
Id: <input id="id" size="1"/> Name: <input id="name" /><br/>
Number: <input id="number" /><br/>
<button onclick="addUser()">Add</button>
</div>
</td>
</tr>
</table>
</div>
It is not necessary to generate the menu list dynamically unless the menu is really dynamic.
Ask if you need explanation on any of the stuff above.
I have created a somehow functional "deeply" nested array filtering functionality. This functionality displays car, which has a color "RED" assigned to them. However the cars, which "pass" the filter is the car, which only has 1 color assigned. How can ensure that arrays within arrays are being checked by the criteria? Would I require creating a loop within loop? The desired outcome would be that if criteria is set to "RED" it will also display the BMW and SUZUKI as these cars also have this color. Any help, suggestions or further links to other posts to achieve the desired outcome would be truly appreciated as I was not able to find anything very useful on my own. The post, which has been most useful has been this one - Filtering an array with a deeply nested array in JS Below I have attached the code snippet of my current code.
const myCars = [
{ name: "BMW",colour: ["White","Red","Black"] },
{ name: "AUDI",colour: ["Yellow","Silver"] },
{ name: "VW",colour: ["Purple","Gold"] },
{ name: "NISSAN",colour: ["White","Black"] },
{ name: "SUZUKI",colour: ["Red"] },
];
for (x in myCars) {
var keys = Object.keys(myCars[x])
var carSpec = myCars.filter(function(fltr) {
return (fltr.colour == "Red");
});
document.getElementById("show1").innerHTML += carSpec[x].name + " " + "has these colours - " + carSpec[x].colour + "<hr />";
}
<p>Car List.</p>
<p id="show"></p>
<p id="show1"></p>
You need to filter by an includes test over the colour array:
const myCars = [
{ name: "BMW",colour: ["White","Red","Black"] },
{ name: "AUDI",colour: ["Yellow","Silver"] },
{ name: "VW",colour: ["Purple","Gold"] },
{ name: "NISSAN",colour: ["White","Black"] },
{ name: "SUZUKI",colour: ["Red"] },
];
const show1 = document.getElementById("show1");
myCars
.filter(({ colour }) => colour.includes('Red'))
.forEach(({ name, colour }) => {
show1.innerHTML += name + " " + "has these colours - " + colour + "<hr />";
});
<p>Car List.</p>
<p id="show"></p>
<p id="show1"></p>
You can use reduce to get an array of cars which have are available in red , then use forEach to loop over it and display the text.
join will join all the contents of an array by the delimiter
const myCars = [{
name: "BMW",
colour: ["White", "Red", "Black"]
},
{
name: "AUDI",
colour: ["Yellow", "Silver"]
},
{
name: "VW",
colour: ["Purple", "Gold"]
},
{
name: "NISSAN",
colour: ["White", "Black"]
},
{
name: "SUZUKI",
colour: ["Red"]
},
];
let hasRed = myCars.reduce(function(acc, curr) {
if (curr.colour.indexOf('Red') !== -1) {
acc.push(curr)
}
return acc;
}, []).forEach((item) => {
document.getElementById("show1").innerHTML += item.name + " " + "has these colours - " + item.colour.join(',') + "<hr />";
})
<p>Car List.</p>
<p id="show"></p>
<p id="show1"></p>
I'm trying to iterate over some JSON that I have included in my file and everything seems to be working fine up until I want to add my icons into each stakebox icon div. Any idea what might be going wrong? I want to add one icon if the value of my JSON object === true and one if the value === false.
$.each(stakeBox, function (i, stakeBoxData) {
var jsonDate = stakeBoxData.data_change_date;
var winLoss = stakeBoxData.win;
var points = stakeBoxData.amount_stakebox;
var winLoss = stakeBoxData.win;
var id = stakeBoxData.id;
if (stakeBoxDay < jsonDate) {
var self = $(this);
console.log(this.win);
$('.stakebox-container').append('\
<div id="' + id + '" class="stakebox-message-container">\
<div id="stakebox-icon"></div>\
<div><h5 id="stakebox-game"></h5></div>\
<div><h5 id="stakebox-points">' + points + '</h5></div>\
</div>\
');
if (this.win === true) {
$('#stakebox-icon').append('<i class="far fa-smile face"></i>');
} else {
$('.stakebox-message-container').css('background', '#a20000');
$('#stakebox-icon').append('<i class="far fa-frown face"></i>');
};
// console.log(i);
} else {
// console.log('nope');
}
});
Here is some of the JSON for reference:
var stakeBox = [{
id: "1",
amount: "40.00",
user_id: "1",
amount_stakebox: "33",
win: true,
data_change_date: "20180229",
username: "bkessler",
game_id: "1380",
team_id: "791",
status: "1"
}, {
id: "2",
amount: "1.00",
user_id: "1",
amount_stakebox: "4124124",
win: false,
data_change_date: "20180429",
username: "bkessler",
game_id: "1380",
team_id: "791",
status: "1"
}];
My multiselect dropdown as below
<div class="col-sm-3 text-left form-group form-group000 form-horizontal" >
<span class="btn-block dropdown-checkbox-example dropdown-checkbox dropdown btn-gray"> </span>
</div>
Jquery code like:
<script src="js/bootstrap-dropdown-checkbox.js"></script>
function list(want, checked) {
var result = [];
for (var i = 0; i < size; i++) {
result.push({
id: i,
label: 'Item #' + i,
isChecked: checked === undefined ? !!(Math.round(Math.random() * 1)) : checked
});
}
return result;
}
var widget, alt;
var tab = [
{ id: "1", label: "Buy.", isChecked: false },
{ id: "2", label: "Sale", isChecked: false },
{ id: "3", label: "Rent", isChecked: false }
];
$('.dropdown-checkbox-example').dropdownCheckbox({
data: tab,
autosearch: true,
title: "My Dropdown Checkbox",
hideHeader: false,
showNbSelected: true,
templateButton: '<a class="dropdown-checkbox-toggle btn-block btn btn-default pad-space4" style=" text-decoration:none;" data-toggle="dropdown" href="#"><span style="color:#000">I want to</span> <span class="dropdown-checkbox-nbselected"></span><b class="caret"></b>'
});
My Issue is I want add selected value in database. so how to get dropdown selected value in Request.?
i'm trying to set width and height to elements in array in java script, for example i have 3 main element in array:"Home","Download","Support" which i call them box, each box should be 600*400 and all picture in home array should be set in this box and that is for all of them, each box in html code is col-lg-3, here is my code, I appreciate if anybody help me.
JavaScript code:
$("document").ready(function () {
var Title = [{ title: "Metro UI template" },
{ title: "Build Windows 8 style websites, with ease" }]
$("#dvTitle").append("<div class='col-lg-9'><a href = '#'><h1>" + Title[0].title + "</h1><h4>" + Title[1].title + "</h4></div> ");
var Menu = [
{ title: "Home", image: '../Icons/1.png' },
{ title: "Download", image: '../Icons/2.png' },
{ title: "Support", image: '../Icons/3.png' }
]
for (i = 0; i < Menu.length; i++) {
$("#dvTitleMenu").append("<div class='col-lg-3'><a href='#'> <h3 > " + Menu[i].title + "</h3><img src=" + Menu[i].image + " style='width:30px; height:30px;'/> </a></div> ");
}
var aMenu =[
{ title: "Home",
items: [{ image: '../Images/1-1.PNG' },
{ image: '../Images/1-2.PNG' },
{ image: '../Images/1-3.PNG' },
{ image: '../Images/1-4.PNG' },
{ image: '../Images/1-5.PNG' }] } ,
{ title: "Download",
items: [{ image: "/Images/2-1.PNG" },
{ image: "/Images/2-2.PNG" },
{ image: "/Images/2-3.PNG" },
{ image: "/Images/2-4.PNG" }] } ,
{
title: "Support",
items: [{image: "/Images/3-1.PNG" },
{ image: "/Images/3-2.PNG" },
{ image: "/Images/3-3.PNG" },
{ image: "/Images/3-4.PNG" }]
}
]
for (i = 0; i < aMenu.length; i++) {
$("#dvcontent").append("<div class='col-lg-12'><a href='#'> <h3> " + aMenu[i].title + "</h3> </a></div> ");
for (var j = 0; j < aMenu[i].items.length; j++) {
$("#dvcontent").append("<a href='#'><img src=" + aMenu[i].items[j].image + " /> </a> ");
}
}
});
HTML code:
<body id="body">
<div id="dvMain">
<div id="dvHeader" class="row">
<div id="dvTitle" class="col-lg-8">
</div>
<div id="dvTitleMenu" class="col-lg-4">
</div>
</div>
<div id="dvcontent" >
<div id="dvHome" class="col-lg-3">
</div>
<div id="dvDownload" class="col-lg-3">
</div>
<div id="dvSupport" class="col-lg-3">
</div>
</div>
</div>