I'm trying to fix my ngdupes error with the checkbox selection. I don't know what's going wrong. Can someone please help? Here is my code:
$scope.GetMultiCheckBox = function GetMultiCheckBox(CheckBoxs) {
var idx = $scope.selectedfunction.indexOf(CheckBoxs);
if (idx > -1) {
$scope.selectedfunction.splice(idx, 1);
}
else {
$scope.selectedfunction.push(CheckBoxs);
}
};
$scope.FilterValueByFunction = function (FunctionVal) {
$scope.Lv7 = [];
if (!$scope.selectedfunction.length == '') {
for (var i = 0; i < $scope.LoadAllData.length; i++) {
for (var j = 0; j < $scope.selectedfunction.length; j++) {
if ($scope.LoadAllData[i].Business_x0020_Checkbox.results.toString().match($scope.selectedfunction[j])) {
$scope.Lv7.push($scope.LoadAllData[i]);
}
}
}
} else {
for (var i = 0; i < $scope.LoadAllData.length; i++) {
$scope.Lv7.push($scope.LoadAllData[i]);
}
}
};
Here is my HTML code for checkboxes:
<ul><li ng-repeat="item in functions">
<input id="{{item}}" type="checkbox" value="{{item}}" ng-disabled="Site.length == 0"
ng-checked="selectedFunction.indexOf(item) > -1"
ng-click="GetMultiCheckBox(item); FilterValueByFunction(item);" autocomplete="off"/></li></ul>
This is the code for the whole data getting filtered based on choices:
<div ng-repeat="item in Lv8|orderBy: 'Category'| filter: SiteFilter
|groupBy: 'Category' | filter: searchBox">
<div id="grad1" ng-show="item.Category_CHANGED">{{item.Category}}
</div>
Thanks!
Related
I am creating a shopping cart with products fetch from a fake json-server. Each time I click the "add to cart" button, I want the product to be push into an array, and if it does exist in the array, I want to increase it by 1
const productGrid = document.querySelector('.grid__product');
const addToCartBtn = document.getElementsByClassName('add-to-cart-btn');
const tableBody = document.querySelector('.table__body');
eventListeners();
//all event listeners
function eventListeners() {
window.addEventListener('DOMContentLoaded', () => {
loadJSON();
loadCart();
})
productGrid.addEventListener('click', purchaseProduct)
}
//load json file into grid display
function loadJSON() {
fetch('http://localhost:3000/products').then(response => {
response.json().then(data => {
let html = '';
data.forEach(product => {
html += `<div class="legacy__items__detail" id='product-${product.id}'><img class='product__img' src="${product.img}" alt="OHUI">
<div class="legacy__items__detail__content legacy-content">
<h4 class='product__name'>${product.productName}</h4><a href="">
<p class='product__category'>${product.name}</p></a><span class="price">${product.price}<small>vnd</small></span>
</div>
<div class="legacy__items__detail__icon">
<div class="legacy-cta">
<button class='add-to-cart-btn'>Mua hàng</button>
<i class="fas fa-heart"></i><i class="fas fa-sync-alt"></i>
</div>
</div>
</div>`;
})
productGrid.innerHTML = html;
})
})}
function purchaseProduct(e) {
if (e.target.classList.contains('add-to-cart-btn')) {
let product = e.target.parentElement.parentElement.parentElement;
getProductInfo(product);
}
}
//get product info after add-cart btn is clicked
function getProductInfo(product) {
let productInfo = {
name: product.querySelector('.product__name').textContent,
imgSrc: product.querySelector('.product__img').src,
category: product.querySelector('.product__category').textContent,
price: parseInt(product.querySelector('.price').textContent),
count: 1,
}
saveProductInStorage(productInfo);
}
function saveProductInStorage(item) {
let products = []
localStorage.setItem('products', JSON.stringify(products));
if(products.indexOf(item) === -1) {
products.push(item)
} else {
item.count++;
}
console.log(products)
}
I have tried several method but the more I try, the more I getting stuck. Can someone please help me with this ?
Edit :
I have succeed in pushing the item in the array and when there is duplicate,the quantity of the item increase, however, I wanna set the products array in the localStorage. Any help is appreciated!
if (products.length === 0) {
products.push(item);
console.log(products);
return;
}
for (let i = 0; i < products.length; i++) {
if (products[i].name === item.name) {
products[i].count++;
console.log(products);
return;
}
}
products.push(item);
}
Slight change to the above answer:
var myContent = document.getElementById("myTextarea").value;
var savedProducts = JSON.parse(localStorage.getItem("products")) || [];
for (var i = 0; i < savedProducts.length; i++) {
if (JSON.parse(myContent).name === savedProducts[i].name) {
savedProducts[i].count++;
alert(`Found Duplicate. Not inserting again ${myContent}`)
} else if (i == savedProducts.length - 1) {
alert(`Inserted ${myContent}`)
savedProducts.push(JSON.parse(myContent));
localStorage.setItem("names", JSON.stringify(savedProducts))
return;
}
}
Tested and seems to be working.
Here is a fully functional code:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h1>Product Retrieve from Locastorage demo</h1>
<textarea id="myTextarea" rows="10" cols="80"></textarea>
<p></p>
<button onclick="saveToCart()">Save to Cart</button>
<button onclick="loadCart()">Load from Cart</button>
<p id="myCart"></p>
<script>
var products = [];
localStorage.setItem("products", JSON.stringify(products))
function saveToCart() {
var productInfo = document.getElementById("myTextarea").value;
var savedProducts = JSON.parse(localStorage.getItem("products")) || [];
if (products.length === 0) {
products.push(JSON.parse(productInfo));
localStorage.setItem("products", JSON.stringify(products))
//console.log(savedProducts.length)
} else {
for (var i = 0; i <= savedProducts.length; i++) {
if (JSON.parse(productInfo).name === savedProducts[i].name) {
savedProducts[i].count++;
//alert(`Found Duplicate at position ${i}. Not inserting again ${productInfo}`)
alert(`${JSON.parse(productInfo).name} already exists`)
} else if (i == savedProducts.length - 1) {
alert(`Inserted ${productInfo} at position ${i}`)
savedProducts.push(JSON.parse(productInfo));
localStorage.setItem("products", JSON.stringify(savedProducts))
console.log(savedProducts.length)
return;
}
}
}
}
function loadCart() {
var products = localStorage.getItem("products");
products = JSON.parse(products)
var col = [];
for (var i = 0; i < products.length; i++) {
for (var key in products[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
///creating a table to load data-- start
var table = document.createElement("table");
var tr = table.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
tr.appendChild(th);
}
for (var i = 0; i < products.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = products[i][col[j]];
}
}
var finalOutput = document.getElementById("myCart");
finalOutput.innerHTML = "";
finalOutput.appendChild(table);
///creating a table to load data-- end
}
</script>
</body>
</html>
I may be misunderstanding the question but if you have all of their purchased products in local storage couldn't you use JSON.parse(localStorage.getItem("products") to get all the products then use a for loop to check if the item being purchased already exists
savedProducts = JSON.parse(localStorage.getItem("products"));
for(var i = 0; i < savedProducts.length; i++){
if(item.name == savedProducts[i].name){
savedProducts[i].count++;
}else if(i == savedProducts.length-1){
savedProducts.push(item);
}
}
localStorage.setItem("products", JSON.stringify(savedProducts));
I haven't tested that but there's an example
I want my bot to choose an item from this site https://www.supremenewyork.com/shop/all/t-shirts, by name and color, but I was able to make it work only when it's choosing by name or color, not both. The code of it looks like this
function pickItem() {
chrome.storage.sync.get("itemName", function(data) {
let items = document.getElementsByClassName("name-link");
for(i = 0; i < items.length; i++) {
if ((items[i].innerHTML).includes(data.itemName)) {
chrome.runtime.sendMessage({redirect: items[i].href});
break;
}
}
})
}
This code is supposed to choose both name and color, but isn't working. I would be very thankful for any hints.
function pickItem() {
let items = document.getElementsByClassName("name-link");
chrome.storage.sync.get(["itemName", "color"], function(data) {
for(i = 0; i < items.length; i++) {
if ((items[i].innerHTML).includes(data.itemName)) {
var name_item_found = items[i];
for(j= 0; j < name_item_found.length; j++) {
if((name_item_found[j].innerHTML).includes(data.color)) {
chrome.runtime.sendMessage({redirect: name_item_found[j].href});
break;
}
}
}
}
})
}
I've found a solution, so I'm posting it here if someone has the same problem in the future.
function pickItem() {
let items = document.getElementsByClassName("name-link");
chrome.storage.sync.get(["itemName", "color"], function(data) {
for(i = 0; i < items.length; i++) {
if(items[i].innerHTML == data.itemName) {
for(j = 0; j < items.length; j++) {
if(items[j].innerHTML == data.color) {
if(items[i].href == items[j].href) {
chrome.runtime.sendMessage({redirect: items[i, j].href})
}
}
}
}
}
})
}
var boxes = document.getElementsByName('toggle');
function markPreceding() {
var curIndex = null;
for (var j = 0; j < boxes.length; j++) {
if (boxes[j].checked) {
curIndex = j;
}
}
}
function checkInputs() {
for (var k = 0; k <= curIndex.length; k++) {
boxes[k].checked = true;
}
}
for (var i = 0; i <= boxes.length; i++) {
boxes[i].onchange = markPreceding;
boxes[i].onchange = checkInputs;
}
<input type="checkbox" id="product-1" name="toggle">
<input type="checkbox" id="product-2" name="toggle">
<input type="checkbox" id="product-3" name="toggle">
<input type="checkbox" id="product-4" name="toggle">
<input type="checkbox" id="product-5" name="toggle">
Have a problem passing this "curIndex" value to checkInputs function.
This should check inputs before checked input and get its value to do it.
Only ES5 synthax needed for this project.
EDIT: The ES5 Syntax way
const boxes = document.getElementsByName('toggle');
boxes.forEach(function(box, I) {
box.onclick = function(e) {
markPreceding(i);
};
});
function markPreceding(i) {
for (var j = 0; j < boxes.length; j++) {
if(j <= i) {
document.getElementById('product-' + (j + 1)).checked = true;
} else {
document.getElementById('product-' + (j + 1)).checked = false;
}
}
}
ORIGINAL:
Try using this:
const boxes = document.getElementsByName('toggle');
boxes.forEach((box, i) => {
box.onclick = (e) => {
markPreceding(i);
};
});
function markPreceding(i) {
for (var j = 0; j < boxes.length; j++) {
if(j <= i) {
document.getElementById(`product-${j + 1}`).checked = true;
} else {
document.getElementById(`product-${j + 1}`).checked = false;
}
}
}
For some reason, there seems to be an issue with updating the inputs through the NodeList array returned by document.getElementsByName. Not sure why, but this code has been verified. See working example here.
I am trying to figure out how to remove all table values from 'dzviokli' that hasnt got same 'majaId' with 'maja.ID'
This is my html
<tbody>
<tr ng-repeat="maja in majas">
<td>{{maja.numurs}}</td>
<td>{{maja.iela}}</td>
<td>{{maja.pilseta}}</td>
<td>{{maja.valsts}}</td>
<td>{{maja.pasts}}</td>
<td><button ng-click="linkedDzivokli(maja)" class="dzivoklap poga">Dzivokli</button></dt>
</tr>
</tbody>
<tbody>
<tr ng-repeat="dz in dzivokli">
<td>{{dz.numurs}}</td>
<td>{{dz.stavs}}</td>
<td>{{dz.ist_sk}}</td>
<td>{{dz.iedz_sk}}</td>
<td>{{dz.pilna_plat}}</td>
<td>{{dz.dziv_plat}}</td>
</tr>
</tbody>
This is my js. The maja.ID is maja from another database and it contais value ID. Table dzivokli has value 'MajaId' and it is linked with table 'maja' value ID.
$http.get("http://localhost:20988/api/maja").success(function (response){$scope.majas = response;});
$http.get("http://localhost:20988/api/dzivoklis").success(function(response){$scope.dzivokli = response;});
var sar = $scope.dzivokli;
var index = maja.ID;
lala(sar,index);
}
function lala(sar,index)
{
for(var i = 0; i < sar.length; i++)
{
if(sar[i].MajaId != index)
{
var x = sar.indexOf(sar[i]);
}
sar.splice(x,1);
}
}
Test with this:
for (var i = 0; i < maja.length; i++) {
seekAndDestroy($scope.dzivokli,majaId, maja[i].ID);
}
function seekAndDestroy(obj, key, value){
for (var i = 0; i < obj.length; i++) {
if (obj[i][key] == value) {
obj.splice(i, 1);
break;
}
}
}
I have figured it out. Thanks jlizanab for answering :)
Here is my js
$scope.linkedDzivokli = function(maja)
{
$http.get("http://localhost:####/api/dzivoklis").success(function(response){
var garums = response.length;
for (var i = 0; i != garums; i++)
{
if (response[i].MajaId == maja.ID) {}
else
{
response.splice(response.indexOf(response[i]), 1);
garums = garums - 1;
i = i - 1;
}
}
$scope.dzivokli = response;
});
}
I've already accomplished selecting htc in home page and coming to another page. Now I want to display whether the selected store value and severdata match (in this case I need to show true). During the on submit event, I want to pass all selected values. I have tried the code below, but its not working for me.
$scope.Selctedstores =window.localStorage.getItem("selectedservices");
console.log($scope.Selctedstores);
//console i am getting htc
var serverData = ["Nokia", "Htc", "Samsung"];
$scope.items = [];
for (var i = 0; i < serverData.length; i++)
{
var modal = {
name: serverData[i],
selected: false
};
$scope.items.push(modal);
}
$scope.check = function()
{
var checkedItems = [];
for (var i = 0; i < $scope.items.length; i++) {
if ($scope.items[i].selected) {
checkedItems.push($scope.items[i].name);
}
}
console.log(checkedItems);
}
html
<div ng-controller="Test1Controller">
<div ng-repeat="item in items">
<input type="checkbox" ng-model="item.selected" /> {{item.name}}
</div>
<input type="button" name="submit" value="submit" ng-click="check()" />
</div>
Before pushing to items array check whether the item is present already in the selected store. If so, then assign selected as true. Hope this helps. Let me know if you have any problem
check updated fiddle
function TodoCtrl($scope) {
var serverData = ["Nokia", "Htc", "Samsung"];
var selectedStore = ["Htc"]
$scope.items = [];
for (var i = 0; i < serverData.length; i++)
{
var modal = {
name: serverData[i],
selected: false
};
if (selectedStore.indexOf(serverData[i]) >= 0) {
modal.selected = true;
}
$scope.items.push(modal);
}
$scope.check = function()
{
var checkedItems = [];
for (var i = 0; i < $scope.items.length; i++) {
if ($scope.items[i].selected) {
checkedItems.push($scope.items[i].name);
}
}
console.log(checkedItems);
}
}
Try
for(var i=0;i<serverData.length;i++)
{
var modal = {
name:serverData[i],
selected:($scope.Selctedstores !== null && $scope.Selctedstores.indexOf(serverData[i]) > -1) ? true : false
};