Adding specific 'badging' to a sku if it is on offer - javascript

I have a list of products that need a badge adding if they are found on a list/category page. I have this so far but it's adding badges to every sku and not the ones specified.
The code I have so far is:
const $discountedProducts = options.state.get('$discountedProducts')
const elibigleSKUs = [
'5981BZ501', 'CBMV03300', 'PCMC03300', 'PCMC46800', 'PCMS03300',
'PCMS46800', 'PCMV03300', 'PCMV46800', 'PKMC03300', 'PKMC46800',
'PKMS46800', 'PKMV03300', 'PKMV46800', 'RACOU4800', 'RAFRX6600',
'RAJUC6000', 'RALWC6001', 'RALWC6002', 'RAMC03300', 'RAMC46800',
'RAMS03300', 'RAMS46800', 'RAMV03300', 'RCMC46800', 'RCMS03300',
'RCMS46800', 'RCMV03300', 'RCMV46800', 'SEBCBH700', 'SECOU4800',
'SEFRX6600', 'SEJUC6000', 'SELWC6000', 'SEMC03300', 'SEMC46800',
'SEMS03300', 'SEMS46800', 'SEMV03300', 'SEMV46800', 'SEOS65100',
'SEOX02702', 'SEOX02704', 'STMC03300', 'STMC46800', 'STMS03300',
'STMS46800', 'STMV03300', 'STMV46800', 'SWCOU4800', 'SEATAY600',
'SEAT65100', 'RAAT65100', 'PKMS03300', 'RAATAY600'
]
const targets = [
'.productCard_mediaContainer'
]
poller(targets, ($products) => {
const $discountedProducts = $products.filter(function () {
const $this = $(this)
const $link = $this.find('.productCard_mediaContainer > a')
const currentSku = String($link.data('code')).toUpperCase()
if (elibigleSKUs.indexOf(currentSku) >= -1) {
return true
}
return false
})
if ($discountedProducts.length) {
$('.productCard_mediaContainer').append('<div class="t028-percent-off productCard_promoLine"><span class="discount"><strong>10%</strong> discount applied</span></div>').addClass('t028');
}
})
So it targets a container and attempts to inject the badge per sku. Apologise if this is not perfect but I am more Design/UX than Dev. Any help would be much appreciated. I can add more info if this is not enough.

I recommend adding console.log() statements in your poller function to see what you're getting. You could do something like this:
if (elibigleSKUs.indexOf(currentSku) >= -1) {
console.log("This SKU is eligible " + currentSku);
return true
}
console.log("This SKU is NOT eligible " + currentSku);
return false
This should give you a place to start.

Related

javascript InnerHTML adding cards only one time

I'm trying to add a bootstrap card inside a div called [itemscontainer] using javascript
by document.getElementById("itemscontainer").innerHTML so i want the cards to be inserted inside the itemscontainer only one time like this :-
but the problem is the items cards keeps reapet them salves more than one time like:-
what i want is to clear the itemscontainer first before adding the cards and this is what i have tried so that the items will be only one cards for each item
// clear function
function clear(){
document.getElementById("ssst").innerHTML = ""
}
// listener append all items to the inventory
window.addEventListener('message', (event) => {
let data = event.data
if(data.action == 'insertItem') {
let name = data.items.name
let count = data.items.count
let icon = data.items.icon
if(document.getElementById("ssst").innerHTML == ""){
clear()
}else{
document.getElementById("ssst").innerHTML +=
"<div class='card holder'>"+
'<div class="card-body">'+
'<img src="icons\\'+icon+'" style="position:absolute;left:15%;width:40px; height:36px;" alt="">'+
'<h4 id="counter">'+count+'</h4>'+
'</div>'+
'<span class="itemname">'+name+'</span>'+
'</div>";'
}
}
})
The real solution is to figure out why you are getting the items more than once. With the information you provided that is impossible for me to answer. So the only thing we can recommend is how to prevent items from being added more than once.
If your messaging system returns duplicates you can determine if you have seen it. If you do, replace it. Otherwise add it.
window.addEventListener('message', (event) => {
const data = event.data;
console.log(data)
if (data.action == 'insertItem') {
let name = data.items.name
let count = data.items.count
let icon = data.items.icon
const html = `
<div class='card holder' data-name="${name}">
<div class="card-body">
<img src="icons/${icon}" style="position:absolute;left:15%;width:40px; height:36px;" alt="${icon}">
<h4 id="counter">${count}</h4>
</div>
<span class="itemname">${name}</span>
</div>`;
const elemExists = document.querySelector(`[data-name="${name}"]`);
if (elemExists) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
elemExists.replaceWith(doc.body);
} else {
document.getElementById("ssst").insertAdjacentHTML("beforeend", html);
}
}
});
window.postMessage({
action: 'insertItem',
items: {
name: 'foo',
count: 1,
icon: 'foo'
}
});
window.postMessage({
action: 'insertItem',
items: {
name: 'bar',
count: 40,
icon: 'barrrrrr'
}
});
window.postMessage({
action: 'insertItem',
items: {
name: 'foo',
count: 1000,
icon: 'foo'
}
});
<div id="ssst"></div>
Why are you using the if statement, what are you checking for?
remove the if statement, I can't see the reason for it to be used here.
clear()
and the rest of your code.

Why when i am searching for something else is deleting the previous contents

Why when you are searching for something else is deleting the previous contents ?For example first you search for egg and show the contents but then when you search for beef the program deletes the egg and shows only beef.Code :
const searchBtn = document.getElementById('search-btn');
const mealList = document.getElementById('meal');
const mealDetailsContent = document.querySelector('.meal-details-content');
const recipeCloseBtn = document.getElementById('recipe-close-btn');
// event listeners
searchBtn.addEventListener('click', getMealList);
mealList.addEventListener('click', getMealRecipe);
recipeCloseBtn.addEventListener('click', () => {
mealDetailsContent.parentElement.classList.remove('showRecipe');
});
// get meal list that matches with the ingredients
function getMealList(){
let searchInputTxt = document.getElementById('search-input').value.trim();
fetch(`https://www.themealdb.com/api/json/v1/1/filter.php?i=${searchInputTxt}`)
.then(response => response.json())
.then(data => {
let html = "";
if(data.meals){
data.meals.forEach(meal => {
html += `
<div class = "meal-item" data-id = "${meal.idMeal}">
<div class = "meal-img">
<img src = "${meal.strMealThumb}" alt = "food">
</div>
<div class = "meal-name">
<h3>${meal.strMeal}</h3>
Get Recipe
</div>
</div>
`;
});
mealList.classList.remove('notFound');
} else{
html = "Sorry, we didn't find any meal!";
mealList.classList.add('notFound');
}
mealList.innerHTML = html;
});
}
It's because you are replacing the contents in the mealList element every time.
A simple workaround would be to retrieve the the innerHTML values before you update it.
Something like
let html = mealList.innerHTML;
rather than starting off empty every time you call the function should do the trick.

How is it possible that piece of code that was working is now ignored?

I have coded a ajax based "JS TABS" containing .JSON file like 10 months ago, now wanted to reuse it, and can't find out why it's not working. I haven't touched it since and don't know where is the bug.
When i click the button to render products nothing prints out - except console telling me: items is undefined = so i moved it inside function changeCategoryItems(categoryId) { } well no errors but nothing renders...can someone help me ?
Here is a codepen reference of what i mean: https://codepen.io/Contemplator191/pen/WNwgypY
And this is JSON : https://api.jsonbin.io/b/5f634e0c302a837e95680846
If codepen is not suitable/allowed here is whole JS for that
let items = [];
const buttons = document.querySelectorAll('button');
const wrapper = document.querySelector('section.products');
buttons.forEach(function (button) {
button.addEventListener('click',event => {
changeCategoryItems(event.target.dataset.category);
});
});
function changeCategoryItems(categoryId) {
let items = [];
const buttons = document.querySelectorAll('button');
const wrapper = document.querySelector('section.products');
const viewItems = (categoryId == 0 ) ? items : items.filter(item => item.category == categoryId);
wrapper.innerHTML = "";
viewItems.forEach(item => {
const div = document.createElement('div');
div.setAttribute("class", "product");
div.innerHTML = createItem(item);
wrapper.appendChild(div);
});
};
function createItem(item) {
return `
<div class="product__img">
<img src="${item.img}" class="">
</div>
<div class="product__name _tc">
<h4 class="">${item.heading}</h4>
</div>
<div class="text-desc product__desc">
<p class="">${item.description}</p>
</div>
<div class="product__bottom-content">
<span class="product__info">${item.info}</span>
${item.btn}
</div>
`
}
fetch('https://api.jsonbin.io/b/5f634e0c302a837e95680846')
.then(function (res) { return res.json() })
.then(function (data) {
items = data.items;
changeCategoryItems(1);
});`
In your fetch you're trying to assign data.items to the items variable but the api doesn't return data with an items node so items is undefined. It's possible the api changed their return format since the last time you used it which would explain why it worked previously.
this seems to fix it
.then(function (data) {
items = data;
changeCategoryItems(1);
});
Your issue is in this line:
items = data.items;
Now, the returned value is an array, hence you can use it as it is.
The updated codepen

How to loop through HTML elements and populate a Json-object?

I'm looping through all the html tags in an html-file, checking if those tags match conditions, and trying to compose a JSON-object of a following schema:
[
{ title: 'abc', date: '10.10.10', body: ' P tags here', href: '' },
{ title: 'abc', date: '10.10.10', body: ' P tags here', href: '' },
{ title: 'abc', date: '10.10.10', body: ' P tags here', href: '' }
]
But I'd like to create the new entry only for elements, classed "header", all the other elements have to be added to earlier created entry. How do I achieve that?
Current code:
$('*').each((index, element) => {
if ( $(element).hasClass( "header" ) ) {
jsonObject.push({
title: $(element).text()
});
};
if( $(element).hasClass( "date" )) {
jsonObject.push({
date: $(element).text()
});
}
//links.push($(element))
});
console.log(jsonObject)
Result is:
{
title: 'TestA'
},
{ date: '10.10.10' },
{
title: 'TestB'
},
{ date: '10.10.11' }
I'd like it to be at this stage something like:
{
title: 'TestA'
,
date: '10.10.10' },
{
title: 'TestB'
,
date: '10.10.11' }
UPD:
Here's the example of HTML file:
<h1 class="header">H1_Header</h1>
<h2 class="date">Date</h2>
<p>A.</p>
<p>B.</p>
<p>С.</p>
<p>D.</p>
<a class="source">http://</a>
<h1 class="header">H1_Header2</h1>
<h2 class="date">Date2</h2>
<p>A2.</p>
<p>B2.</p>
<p>С2.</p>
<p>D2.</p>
<a class="source">http://2</a>
Thank you for your time!
Based on your example Html, it appears everything you are trying to collect is in a linear order, so you get a title, date, body and link then a new header with the associated items you want to collect, since this appears to not have the complication of having things being ordered in a non-linear fasion, you could do something like the following:
let jsonObject = null;
let newObject = false;
let appendParagraph = false;
let jObjects = [];
$('*').each((index, element) => {
if ($(element).hasClass("header")) {
//If newObject is true, push object into array
if(newObject)
jObjects.push(jsonObject);
//Reset the json object variable to an empty object
jsonObject = {};
//Reset the paragraph append boolean
appendParagraph = false;
//Set the header property
jsonObject.header = $(element).text();
//Set the boolean so on the next encounter of header tag the jsobObject is pushed into the array
newObject = true;
};
if( $(element).hasClass( "date" )) {
jsonObject.date = $(element).text();
}
if( $(element).prop("tagName") === "P") {
//If you are storing paragraph as one string value
//Otherwise switch the body var to an array and push instead of append
if(!appendParagraph){ //Use boolean to know if this is the first p element of object
jsonObject.body = $(element).text();
appendParagraph = true; //Set boolean to true to append on next p and subsequent p elements
} else {
jsonObject.body += (", " + $(element).text()); //append to the body
}
}
//Add the href property
if( $(element).hasClass("source")) {
//edit to do what you wanted here, based on your comment:
jsonObject.link = $(element).next().html();
//jsonObject.href= $(element).attr('href');
}
});
//Push final object into array
jObjects.push(jsonObject);
console.log(jObjects);
Here is a jsfiddle for this: https://jsfiddle.net/Lyojx85e/
I can't get the text of the anchor tags on the fiddle (I believe because nested anchor tags are not valid and will be parsed as seperate anchor tags by the browser), but the code provided should work in a real world example. If .text() doesn't work you can switch it to .html() on the link, I was confused on what you are trying to get on this one, so I updated the answer to get the href attribute of the link as it appears that is what you want. The thing is that the anchor with the class doesn't have an href attribute, so I'll leave it to you to fix that part for yourself, but this answer should give you what you need.
$('*').each((index, element) => {
var obj = {};
if ( $(element).hasClass( "header" ) ) {
obj.title = $(element).text();
};
if( $(element).hasClass( "date" )) {
obj.date = $(element).text()
}
jsonObject.push(obj);
});
I don't know about jQuery, but with JavaScript you can do with something like this.
const arr = [];
document.querySelectorAll("li").forEach((elem) => {
const obj = {};
const title = elem.querySelector("h2");
const date = elem.querySelector("date");
if (title) obj["title"] = title.textContent;
if (date) obj["date"] = date.textContent;
arr.push(obj);
});
console.log(arr);
<ul>
<li>
<h2>A</h2>
<date>1</date>
</li>
<li>
<h2>B</h2>
</li>
<li>
<date>3</date>
</li>
</ul>
Always use map for things like this. This should look something like:
let objects = $('.header').get().map(el => {
return {
date: $(el).attr('date'),
title: $(el).attr('title'),
}
})

Dynamic query to take input from user and do filtering from the database node.js

enter image description hereWhat I'm trying is fetching columns from the user to which the user entered, The Good thing is Columns are getting fetched and the bad thing is the columns that I had applied conditions are not working.Can anyone help me out? I want a query that works for the filter option as in many websites to filter any product or something.
Newbie here!!!
routes.post('/FilterCandidate',function(req,res){
var fetchparameter={};
var dynamicquery={author : req.user.username};
if(req.user.username){
if(req.body.ConsultantName){
fetchparameter["ConsultantName"] = req.body.ConsultantName;
}
if(req.body.Location){
fetchparameter["Location"] = req.body.Location;
}
if(req.body.JobRole){
fetchparameter["JobRole"] = req.body.JobRole;
}
if(req.body.Skills){
fetchparameter["Skills"] = req.body.Skills.split(',');
}
if(req.body.VisaStatus){
fetchparameter["VisaStatus"] = req.body.VisaStatus;
}
if(req.body.BillingRate){
fetchparameter["BillingRate"] = req.body.BillingRate;
}
if(req.body.experience){
fetchparameter["experience"] = req.body.experience;
}
if(req.body.jobtype){
fetchparameter["jobtype"] = req.body.jobtype;
}
if(req.body.Availability){
fetchparameter["Availability"] = req.body.Availability;
}
if(req.body.experience){
fetchparameter["Salary"] = req.body.Salary;
}
if(req.body.Salarytype){
fetchparameter["Salarytype"] = req.body.Salarytype;
}
}
/* This below code for conditions is not working*/
for(var key in fetchparameter){
if (key== "Salary" ){
dynamicquery[key] = {$gte :fetchparameter[key]};
}
if(key == "Skills"){
dynamicquery [key] = {$in : fetchparameter[key]};
}
if(key == "experience"){
dynamicquery[key] = {$gte :fetchparameter[key]};
}
else{
dynamicquery[key] = fetchparameter[key];
}
}
console.log(dynamicquery);
Candidate.aggregate([ {$match : dynamicquery }],(err,docs) =>{
res.render('FilteredCandidate',{'Candidates' : docs});
});
});
This is what I'm getting output to refer to the attached image
i think you should make a match object array it will make your code more neat and hoping that it will solve your problem
Ex:
var match = {$and:[]};
if(any condition satisfy){
match.$and.push({}) //condition
}
and most important do check if match.$and array must not be empty if it is then delete match.$and. this procedure will help you to maintain your query better provides more flexibility.

Categories