Sort items on e-commerce site by item price? - javascript

I'm trying to use Javascript's getAttribute to get the item price. I'm a huge noob so I just used getAttribute and changed the <h2> classes to the item prices. That only grabs the first item price though, how can I get it to grab all of the prices and store them as an array for sorting or something?
Here's some of my HTML:
<div class="col-sm-4">
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center">
<img src="images\site_images\bag3.jpg" alt="" height="249" />
<h2 class="881.10">$881.10</h2>
<h5>Authentic New Gucci ($1690) Micro-GG "Vernice" Crossbody w/Strap #309617, NWT</h5>
<i class="fa fa-shopping-cart"></i>Add to Cart
</div>
<div class="col-sm-4">
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center">
<img src="images\site_images\bag4.jpg" alt="" height="249" />
<h2 class="569.05">$569.05</h2>
<h5>AUTHENTIC NWT ($819) Gucci GG Large Brown Denim Tassell Tote #336660, w/Gft Rcpt</h5>
<i class="fa fa-shopping-cart"></i>Add to Cart
</div>
<div class="col-sm-4">
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center">
<img src="images\site_images\bag5.jpg" alt="" height="249" />
<h2 class="559.00">$559.00</h2>
<h5>Authentic Gucci GG Micro-Guccissima Leather Tote #309613 w/Gft Rcpt,NWT</h5>
<i class="fa fa-shopping-cart"></i>Add to Cart
</div>
and
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
And here is my Javascript code I'm using to get the item prices:
function myFunction() {
var x = document.getElementsByTagName("H2")[0].getAttribute("class");
document.getElementById("demo").innerHTML = x;
}
I'm a huge novice as you can see, so please try to make your answers not so complex if you could. :) thanks!

Save the prices to an array, and then use .sort() to sort the array. Note that the .sort() function sorts alphabetically by default, so you have to write your own comparator function for integers. for example, to sort in ascending order:
function sortNumber(a,b) {
return a - b;
}
Once you have all the prices saved to an array, iterate through the array and convert them to numbers using a unary plus:
var items = document.getElementsByTagName("H2");
var prices = [];
for(var i = 0; i < items.length; i++){
prices.push( +items[i].getAttribute("class"));
}
Alternatively, you can use .parseInt().
see an example here: http://codepen.io/anon/pen/VeKyMe

Why would you store the value of the prices as a class attribute in the first place? By doing so, you are going against the main purpose of the class attribute, which is to group elements that share something in common.
I'd suggest using the same value for the class attribute for all the tags that contain a price, for example:
...
<h2 class="price">$111.11</h2>
...
<h2 class="price">$222.22</h2>
...
Then you can grab all the elements that belong to the same class, in one call, and iterate over them:
javascript:
var items = getElementsByClassName('price')
jQuery:
var items = $('.price')
If for any reason it is important to you to store the value in some attribute, you could use the custom data- attributes, for example:
<h2 class="price" data-value="111.11">$111.11</h2>
which could be accessed later:
javascript:
<element>.getAttribute('data-value')
jQuery:
<element>.data('value');

Related

Add a Like + Sort Function to existing dynamic funcion

I wrote a function that dynamically creates a webpage for me based on a json database.
Now I want to add 2 functions:
If you click the like img (its got the id button) the like counter should increase on the webpage by 1. Pretty easy just a on(click) with jQuery variable++ and then .text(variable)
A sort function - based on the likes one item received, you should be able to sort it (most liked div first, 2nd, 3rd....
I can write it for each individually with individual variables when I give all the like buttons and outputs a separate id but I wanted to make it dynamic so if you add new data to json file it dynamically works with the like and sort function.
The likes are not saved anywhere for now.
Since sitting on it for 3h and google so much and so much stackoverflow I think I overloaded my brain with different stuff and now nothing seems to work ^^
function filmInsert(insert) {
$.each(film, function(i, data) { //.each statt loop
let box =
`<div class="boxwrapper">
<div class="imgbox">
<img src="${data.img}" alt="${data.titel}">
</div>
<div class="textbox">
<h3>${data.titel}</h3>
<p>${data.beschreibung}</p>
<p> <a id="button${data.id}">
<img src="img/budspencer_official.png"> Like
</a>
<span class="output${data.id}">${data.likes}</span>
</p>
</div>
</div>`;
insert.append(box);
});
}
I've added a container element for the boxwrapper items as I assume you have one and as it's better to have one instead of just adding the sorted items to the body of the HTML document.
$(document).on("click", ".textbox a", function() {
let likes = parseInt($(this).closest(".textbox").find("span").text());
$(this).closest(".textbox").find("span").text(likes + 1);
});
$("#sort").on("click", function() {
let divs = $(".boxwrapper")
let sorted = divs.sort(function(a, b) {
return $(a).find("span").text() < $(b).find("span").text() ? 1 : -1;
});
$(".container").html(sorted);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="boxwrapper">
<div class="imgbox">
<img src="example.gif" alt="Title">
</div>
<div class="textbox">
<h3>Titel</h3>
<p>Description</p>
<p> <a id="button1">
<img src="https://dummyimage.com/40x40/000/fff&text=1"> Like
</a>
<span class="output1">0</span>
</p>
</div>
</div>
<div class="boxwrapper">
<div class="imgbox">
<img src="example.gif" alt="Title">
</div>
<div class="textbox">
<h3>Titel 2</h3>
<p>Description 2</p>
<p> <a id="button2">
<img src="https://dummyimage.com/40x40/000/fff&text=2"> Like
</a>
<span class="output2">0</span>
</p>
</div>
</div>
</div>
<button id="sort">
Sort
</button>

Define a dynamic output inside a variable?

I hope the title is not wrongfully put or misleading. What I want to do, in order to cut down unnecessary repetition of code, is something like this:
const predefinedOutput = "for(let i = 0; i < movie.length; i++) {
output += `<div class="card">
<div class="overlay">
<div class="movie">
<h2>${movie[i].title}</h2>
<p><strong>Rating:</strong> ${movie[i].vote_average}</p>
<p><strong>Release date:</strong> ${movie[i].release_date}</p>
<a onclick="movieSelected('${movie[i].id}')" href="#">Details</a>
</div>
</div>
<div class="card_img">
<img src="http://image.tmdb.org/t/p/w300/${movie[i].poster_path}" onerror="this.onerror=null;this.src='../images/imageNotFound.png';">
</div>
</div>`;
};
How can I, if its doable at all, to sort of pre-define an output that includes a forloop, that will be then used in an API call, so I don't make duplicates of the code above for different searches (page change, genre change etc.)? Thanks in advance.
Try the following example. Don't know what movies is so had to make something of it. In this example it should be an array. You could also use .map() but then the movies should be an object. map and forEach do the same as a for loop
<script>
movies.forEach( movie => {
output += `<div class="card">
<div class="overlay">
<div class="movie">
<h2>${movie.title}</h2>
<p><strong>Rating:</strong> ${movie.vote_average}</p>
<p><strong>Release date:</strong> ${movie.release_date}</p>
<a onclick="movieSelected('${movie.id}')" href="#">Details</a>
</div>
</div>
<div class="card_img">
<img src="http://image.tmdb.org/t/p/w300/${movie.poster_path}" onerror="this.onerror=null;this.src='../images/imageNotFound.png';">
</div>
</div>`;
});

Jquery: How to clone <div> based on the count?

I am trying to use jquery clone() for displaying cards on my web page. When the page loads it has to clone card div based on the count of rooms in that particular location. I hardcoded count as roomcount. I tried using simple for loop as per https://stackoverflow.com/a/12835644/6915446, However it doubles the count of divs each time. Please provide me right inputs.
<div class="container-fluid">
<div class="row-fluid">
<div class="col-lg-2">
<div class="card">
<h6 class="card-header">NC001
<ul class="card-header-pills pull-xs-right">
<span class="badge badge-primary" aria-hidden="true">2</span>
<!-- <span class="glyphicon glyphicon-user" aria-hidden="true"></span> -->
</ul>
</h6>
<div class="card-block" id="scrollCard">
<h4 class="card-title"></h4>
<!-- <p class="card-text">ICU : 12.00 AM</p>
<p class="card-text">VEN : 1.00 AM</p> -->
</div>
</div>
<script>
var roomcount = 3;
$(document).ready(function() {
for(var i=0; i< roomcount; i++) {
$(".col-lg-2").clone().appendTo(".row-fluid");
}
});
</script>
</div>
Thanks.
When the count is 2, it clones to display 4 divs:
When the count is 3, it clones to displays 8 divs:
I think you might be cloning an array?
After you have cloned
$(".col-lg-2")
once it becomes an array, so when you clone it again you get 4?
Try using
$(".col-lg-2:first").
Tom
When you select an element by it's class name, jquery returns an array of all the matching objects.
So once you've cloned an item with the same class name, the next time you call $(".col-lg-2"); it will actually fetch 2 items and clone them, and the next time it will fetch 4 items and clone them etc.
To avoid it (and as a best practice) you should cache the element you are cloning:
var roomcount = 3,
$cloned = $('.col-lg-2');
for(var i = 0; i < roomcount; i++) {
$cloned.clone().appendTo('.row-fluid');
}
that way you always clone just that one object you cached.
NOTE: make sure you don't have an id on the cloned object since you'll be creating multiple items with the same id and id should be unique
The clone() method makes a copy of selected elements, including child nodes, text and attributes.
You can save the value of $(".col-lg-2") in a variable, and clone it, these way you are improving performance as you are not going to query the DOM multiple times:
var roomcount = 3,
$colLg2 = $('.col-lg-2');
for(var i = 0; i < roomcount; i++) {
$colLg2.clone().appendTo('.row-fluid');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row-fluid">
<div class="col-lg-2">
<div class="card">
<h6 class="card-header">NC001
<ul class="card-header-pills pull-xs-right">
<span class="badge badge-primary" aria-hidden="true">2</span>
<!-- <span class="glyphicon glyphicon-user" aria-hidden="true"></span> -->
</ul>
</h6>
<div class="card-block" id="scrollCard">
<h4 class="card-title"></h4>
<!-- <p class="card-text">ICU : 12.00 AM</p>
<p class="card-text">VEN : 1.00 AM</p> -->
</div>
</div>
</div>
</div>

Sort HTML String

I have this bit of HTML code.
<div class="container">
<div class="single-result">
<span class="flight-no">VL2100</span>
<span class="cabin">Economy</span>
<span class="price">35000</span>
</div>
<div class="single-result">
<span class="flight-no">VL2101</span>
<span class="cabin">Economy</span>
<span class="price">40000</span>
</div>
<div class="single-result">
<span class="flight-no">VL2100</span>
<span class="cabin">Economy</span>
<span class="price">22000</span>
</div>
<div class="single-result">
<span class="flight-no">VL2100</span>
<span class="cabin">Economy</span>
<span class="price">14500</span>
</div>
</div>
How do I sort it -- based on price -- using Javascript? Please, don't ask me for my JS code. My only thought was to use the bubble sort algorithm. But then, bubble sort works only on sorted arrays and my HTML string isn't sorted. Any suggestions, pointers and / or code will be appreciated.
Create an array and insert for each element 2 fields, the HTML element and the price, sort the array, re-insert the elements after sorting to conainer after make it empty:
var elements = document.querySelectorAll('.single-result');
var sortable = [];
for (i=0;i<elements.length;i++){
sortable.push([elements[i], elements[i].querySelector('.price').textContent]);
}
sortable.sort(function(a, b) {return a[1] - b[1]});
container = document.querySelector('.container');
container.innerHTML = "";
sortable.forEach(function(item) {
container.appendChild(item[0]);
});

How to create an array of divs with content?

I'm trying to create an array of nested divs, in which I only need to change 3 values when writing the divs to the document (html).
My divs look like this:
<div class="item">
<div class="item-h"> <a class="item-anchor" href="1_water_bottle.html">
<div class="item-image"> <img class="item-image-first" src="images/img_1_water_bottle.png" alt="">
<div class="item-meta">
<h2 class="title">Water Bottle 1</h2>
<span class="item-arrow"></span> </div>
</div>
</a> </div>
</div>
I need to create an array of about 50 items, and then use the document.write function to write 4 of those arrays for each page, as a section for "similar stuff".
I searched on stackoverflow, and came up with :: this page :: , which explains how to create an array in javascript, and then found another script that uses the document.write function.
The script uses an array of categories, to populate a form selection. And it does so, but using an array : (var categories = new Array("a1", "a2", "a3", ...) and so on.
for(var hi=0; hi<categories.length; hi++)
document.write("<option value=\""+categories[hi]+"\">"+categories[hi]+"</option>");
Could I use these two scripts to populate a section with 4 items from the array of the divs?
If so, then how could I do it? I know it can be done in php, but don't know if this can be done in javascript.
I tried, and created this array in notepad++, but the code wasn't recognized as a string, per array element...
var array_divs = [
$('<div class="item">
<div class="item-h"> <a class="item-anchor" href="1_water_bottle.html">
<div class="item-image"> <img class="item-image-first" src="images/img_1_water_bottle.png" alt="">
<div class="item-meta">
<h2 class="title">Water Bottle 1</h2>
<span class="item-arrow"></span> </div>
</div>
</a> </div>
</div>') ,
$('<div class="item">
<div class="item-h"> <a class="item-anchor" href="1_water_bottle_2.html">
<div class="item-image"> <img class="item-image-first" src="images/img_1_water_bottle_2.png" alt="">
<div class="item-meta">
<h2 class="title">Water Bottle 2</h2>
<span class="item-arrow"></span> </div>
</div>
</a> </div>
</div>')
]
Trying to populate the section, with selective items from the array, for example:
document.write(array_divs[1],array_divs[2]);
I haven't tried this, but since notepad++ didn't treat my div as a string, I had to search again... but couldn't find any info regarding this.
Thanks for any help.
-

Categories

Resources