I'm trying to order the different products from a website but can't do it correctly.
Basically I need to get the price of each one and order them from the most expensive one to the least one.
I tried the following code but it disappears everything and keeps not ordering them in the correct way:
var divList = $(".block-level.h2");
divList.sort(function(a, b){
return $(a).data(".block-level.h2")-$(b).data(".block-level.h2")
});
$(".grid").html(divList);
I don't have access to modify the HTML so it has to be done with the code I have now, only can add things through jQuery.
Can someone give me a tip or help me out please?
Thank you.
For your request to sort the product grid items, here is the jQuery code that you can use.
var values = [];
$('.block-level.h2').each(function() {
var temp = Array();
temp['value'] = parseInt($(this).html().replace('$',''));
temp['element'] = $(this).closest('.grid-item');
values.push(temp);
});
values.sort(function(a,b) { return b.value - a.value; });
var sortedHtml = '';
$.each(values, function(index, obj) {
if((index+1)%3==1) {
sortedHtml+=('<div class="grid product-cards__row"><div class="grid-item one-third palm-one-whole product-cards__item">'+$(obj.element).html()+'</div>');
} else if((index+1)%3==0) {
sortedHtml+=('<div class="grid-item one-third palm-one-whole product-cards__item">'+$(obj.element).html()+'</div></div>');
} else {
sortedHtml+=('<div class="grid-item one-third palm-one-whole product-cards__item">'+$(obj.element).html()+'</div>');
}
});
$('.product-cards').html(sortedHtml);
Hope this helps!
You can achieve this by the following code-
var values = Array();
$('.block-level.h2').each(function() {
values.push(parseInt($(this).html().replace('$','')));
});
values.sort(function(a, b){return b-a});
In your code above - the main problem is with $(a).data(".block-level.h2") since its trying to find an attribute with name data-.block-level.h2 in element a which doesn't exist. That's why the empty result.
Related
Here is a simple example of a group of divs that can be sorted either by their HTML content or by custom attribute values:
Sort alphabetically by HTML content
Sort low to high by the value of the attribute "sortweight"HTML:
I have tried following code and got error
ReferenceError: $$ is not defined
HTML
<div id="sortexample">
<div class="sortitem" sortweight="5">Pears [sortweight: 5]</div>
<div class="sortitem" sortweight="3">Apples [sortweight: 3]</div>
<div class="sortitem" sortweight="1">Cherries [sortweight: 1]</div>
<div class="sortitem" sortweight="4">Oranges [sortweight: 4]</div>
<div class="sortitem" sortweight="2">Strawberries [sortweight: 2]</div>
</div>
JavaScript:
// sort all divs with classname 'sortitem' by html content
function sort_div_content() {
// copy all divs into array and destroy them in the page
divsbucket = new Array();
divslist = $$('div.sortitem');
for (a=0;a<divslist.length;a++) {
divsbucket[a] = divslist[a].dispose();
}
// sort array by HTML content of divs
divsbucket.sort(function(a, b) {
if (a.innerHTML.toLowerCase() === b.innerHTML.toLowerCase()) {
return 0;
}
if (a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase()) {
return 1;
} else {
return -1;
}
});
// re-inject sorted divs into page
for (a=0;a<divslist.length;a++) {
divsbucket[a].inject($('sortexample'));
}
}
// sort by attributes - usage for our example: sort_div_attribute('sortweight');
function sort_div_attribute(attname) {
// copy all divs into array and destroy them in the page
divsbucket = new Array();
divslist = $$('div.sortitem');
for (a=0;a<divslist.length;a++) {
divsbucket[a] = new Array();
// we'vev passed in the name of the attribute to sort by
divsbucket[a][0] = divslist[a].get(attname);
divsbucket[a][1] = divslist[a].dispose();
}
// sort array by sort attribute content
divsbucket.sort(function(a, b) {
if (a[0].toLowerCase() === b[0].toLowerCase()) {
return 0;
}
if (a[0].toLowerCase() > b[0].toLowerCase()) {
return 1;
} else {
return -1;
}
});
// re-inject sorted divs into page
for (a=0;a<divslist.length;a++) {
divsbucket[a][1].inject($('sortexample'));
}
}
I dont know why i got this error
On the fifth line, it says divslist = $$('div.sortitem');, but $$ is not defined. You have to use $ instead of $$.
divslist = $('div.sortitem'); This would be better
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
I am trying to make a news object and in that section in which there are separate sub-section so it will look like this. user can add and remove subsection.
and when I press the save button it should send the data as following json structure seperating each subsection by ||.
{"news": {
"section1": ["ABCDE||FGHI||JKLM"],
"section2": ["NOPQ"],
"section3": ["RSTU"]
}
}
and when use save the data it should get saved and when the user open that page again it should be as last saved.
This is what I have tried so far.
I have tried to make a div and then wrap test area in it in ng-repeat but it seems like it should be it a table.
// For adding the subsection
$scope.section1 = [];
$scope.addsection1=function(){
$scope.section1.push({});
}
// For removing the subsection
$scope.removesection1 = function(id){
var indexToRemove;
for(i = 0; i < $scope.section1.length; i++){
if($scope.section1[i].id === id){
indexToRemove = i;
}
$scope.section1.splice(indexToRemove, 1);
}
}
<div class="section-div flex-column">
<div class="flex-row">
<h4 style="flex-grow: 2;">New Updates</h4>
<button class="add-btn" ng-click="addsection1()">+Add field</button>
</div>
<textarea ng-repeat="section in section1"
style="margin: 7px;border: 1px solid #00000047;border-radius: 4px;"
name="" id="">
</textarea>
</div>
Please help me I m a beginner in the angularjs. Thanks in advance.
send the data as following json structure seperating each subsection by ||
One approach is to use array.join:
var arr = ["ABCDE", "FGHI", "JKLM"];
var obj = { news: { section1: [arr.join("||")] } };
console.log(obj);
Conversely, to receive, use string.split:
var obj = { news: { section1: ["ABCDE||FGHI||JKLM"] } };
var arr = obj.news.section1[0].split("||");
console.log(arr);
I have some HTML:
<div id="bin">
<span class="item1 selectMe">1</span>
<span class="item2 selectMe">2</span>
<span class="item3 dontSelectMe">3</span>
</div>
I would like to return an array with the values in the span elements which contain the selectMe class. This is what I've written:
var values = [];
$('#bin span.selectMe').each(function() {
values.push($(this).text());
});
However, when I print values to the console, it is always empty. Any thoughts on why I am not iterating through the bin?
What you have should work, but here is a more elegant solution:
var values = $('#bin span.selectMe').map(function() {
return $(this).text();
}).get();
The following should work, however what you paste above should seem to also:
var values = $('#bin span.selectMe').map(function(){
return $(this).html();
});
var values = [];
$('#bin').find('span.selectMe').each(function() {
values.push($(this).text());
});
Following is the repetivite html structure that i have in my template:
<div class="mystyle" data-id= "11002">
<div class="style1-header"><h6>Change Status of Task</h6></div>
<p class="style1-content">Seriously Change Status of Task</p>
<p class="style2-content" style="visibility:hidden">12</p>
</div>
The above is the html structure that keeps repeating in my html template. I wanted these things to be sorted based on the numbers 12 as in the above case.
How can i do it with jquery. The fiddle is available here.
Use JavaScript's Array.sort method to sort an array of the divs.
var $divs = $('div.mystyle').get().sort(function(a,b){
var aKey = +$(a).find('p.style2-content').text(),
bKey = +$(b).find('p.style2-content').text();
return aKey - bKey;
});
Then append the now sorted array to the DOM.
$('body').append($divs);
var $elements = $("div.mystyle");
function sortFn(a, b) {
var aText = $(a).find("p:hidden").text();
var bText = $(a).find("p:hidden").text();
return aText > bText ? 0 : 1;
}
$elements.sort(sortFn);