Jquery - each get value, Find difference and convert to array - javascript

Used below HTML & JS code to get each value of base currency and member currency.
Need to get Memberprice value by finding a difference between base currency - member currency. Some times member-price will not exist. If condition to check and remove that base-currency from display. Then convert memberprice each value in array.
But, below code.. str1 & str2 outputs are coming as expected. But, memberprice difference get only first value. Not all.
Please help to guide and get a output in array format of extracted value like below based on example HTML shared.
[275, 258, 365, 348, 460] -- 500 will be not there as there is no member-price div
var str1 = "";
var str2 = "";
var memberprice = "";
var arrayKeys = [];
var titleKeys = [];
var title = "";
$('.list-item').each(function(){
str1 += $(this).find('.right-container .base-currency .price').attr('data-base-price') + ",";
str2 += $(this).find('.right-container .member-currency .price').attr('data-base-price') + ",";
console.log('str1: ', str1);
console.log('str2: ', str2);
memberprice += str1 - str2;
console.log(memberprice);
title += $(this).find('.left-container h3').html() + ",";
// need to insert these values in array get memberprice -> str1 - str2. If membercurrency exists minus. Other display only basecurrency.
//output have to be like [275, 258, 365, 348, 500, 460]
arrayKeys.push(memberprice);
//Title in array
titleKeys.push(title);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-item">
<div class="left-container">
<h3>Product Title 1</h3>
Title 1 Link
</div>
<div class="right-container">
<div class="price-list">
<div class="base-currency">
<div class"price" data-base-currency='300'>300 USD</div>
</div>
<div class="member-currency">
<div class"price" data-base-currency='25'>25 USD</div>
</div>
</div>
<div class="price-list">
<div class="base-currency">
<div class"price" data-base-currency='280'>280 USD</div>
</div>
<div class="member-currency">
<div class"price" data-base-currency='22'>22 USD</div>
</div>
</div>
</div>
</div>
<div class="list-item">
<div class="left-container">
<h3>Product Title 2</h3>
Title 2 Link
</div>
<div class="right-container">
<div class="price-list">
<div class="base-currency">
<div class"price" data-base-currency='400'>400 USD</div>
</div>
<div class="member-currency">
<div class"price" data-base-currency='35'>35 USD</div>
</div>
</div>
<div class="price-list">
<div class="base-currency">
<div class"price" data-base-currency='380'>380 USD</div>
</div>
<div class="member-currency">
<div class"price" data-base-currency='32'>32 USD</div>
</div>
</div>
</div>
</div>
<div class="list-item">
<div class="left-container">
<h3>Product Title 3</h3>
Title 3 Link
</div>
<div class="right-container">
<div class="price-list">
<div class="base-currency">
<div class"price" data-base-currency='500'>500 USD</div>
</div>
</div>
<div class="price-list">
<div class="base-currency">
<div class"price" data-base-currency='470'>470 USD</div>
</div>
<div class="member-currency">
<div class"price" data-base-currency='10'>10 USD</div>
</div>
</div>
</div>
</div>

You can loop through price-list div and get value from currency and base using find('.base-currency .price') same for other then subtract that values and add them inside arrays . Also , you need check if title already exist inside title array to avoid any duplicate.
Demo Code :
var str1 = "";
var str2 = "";
var memberprice = "";
var arrayKeys = [];
var titleKeys = [];
var title = "";
//loop through price list divss
$('.price-list').each(function() {
//get value from base & member if exist else take 0
str1 = ($(this).find('.base-currency .price').attr('data-base-currency')) ? parseInt($(this).find('.base-currency .price').attr('data-base-currency')) : 0;
str2 = ($(this).find('.member-currency .price').attr('data-base-currency')) ? parseInt($(this).find('.member-currency .price').attr('data-base-currency')) : 0;
console.log('str1: ', str1);
console.log('str2: ', str2);
memberprice = str1 - str2;
console.log(memberprice);
//get title
title = $(this).closest(".list-item").find('.left-container h3').html();
//check if member is not 0 (means not exist..)
if (str2 != 0) {
arrayKeys.push(memberprice);
}
//check if prduct name exist in title array
if ($.inArray(title, titleKeys) === -1) {
titleKeys.push(title); //push same
}
});
console.log(titleKeys)
console.log(arrayKeys)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-item">
<div class="left-container">
<h3>Product Title 1</h3>
Title 1 Link
</div>
<div class="right-container">
<div class="price-list">
<div class="base-currency">
<div class="price" data-base-currency='300'>300 USD</div>
</div>
<div class="member-currency">
<div class="price" data-base-currency='25'>25 USD</div>
</div>
</div>
<div class="price-list">
<div class="base-currency">
<div class="price" data-base-currency='280'>280 USD</div>
</div>
<div class="member-currency">
<div class="price" data-base-currency='22'>22 USD</div>
</div>
</div>
</div>
</div>
<div class="list-item">
<div class="left-container">
<h3>Product Title 2</h3>
Title 2 Link
</div>
<div class="right-container">
<div class="price-list">
<div class="base-currency">
<div class="price" data-base-currency='400'>400 USD</div>
</div>
<div class="member-currency">
<div class="price" data-base-currency='35'>35 USD</div>
</div>
</div>
<div class="price-list">
<div class="base-currency">
<div class="price" data-base-currency='380'>380 USD</div>
</div>
<div class="member-currency">
<div class="price" data-base-currency='32'>32 USD</div>
</div>
</div>
</div>
</div>
<div class="list-item">
<div class="left-container">
<h3>Product Title 3</h3>
Title 3 Link
</div>
<div class="right-container">
<div class="price-list">
<div class="base-currency">
<div class="price" data-base-currency='500'>500 USD</div>
</div>
</div>
<div class="price-list">
<div class="base-currency">
<div class="price" data-base-currency='470'>470 USD</div>
</div>
<div class="member-currency">
<div class="price" data-base-currency='10'>10 USD</div>
</div>
</div>
</div>
</div>

Related

Getting data from html string and push to array

So i'm making a post request and the response is a string of html and i'm trying to get the data from the "dropUser" part of the html string but i'm having a little trouble and was hoping maybe someone could help me or point me in the right direction.
My goal is to get the data from the "dropUser" html string and push them to an array.
For an example the ID 4289985, and username 'MeowCat i want to get all of them and push to an array.
let str = `<div id="container_user">
<div class="user_count">
<div class="bcell">
Online <span class="ucount back_theme">4</span>
</div>
</div>
<div class="online_user">
<div onclick="dropUser(this,5,'ChatAveBot',1,1,'ZZ','','0','');" class="avtrig user_item ">
<div class="user_item_avatar"><img class="avav acav avsex nosex " src="/avatar/default_avatar.png" /> </div>
<div class="user_item_data">
<p class="username user ">ChatAveBot</p>
</div>
<div class="user_item_icon icrank"><img src="default_images/rank/bot.svg" class="list_rank" title="Bot" /></div>
</div>
<div onclick="dropUser(this,3754679,'Fantastic',1,0,'ZZ','','14','');" class="avtrig user_item ">
<div class="user_item_avatar"><img class="avav acav avsex nosex " src="/avatar/avatar_user3754679_1638955491.jpg" /> </div>
<div class="user_item_data">
<p class="username bcolor1 bnfont7">Fantastic</p>
<p class="text_xsmall bustate bellips">TheDD7デイビスになる =🚮</p>
</div>
</div>
<div onclick="dropUser(this,4290052,'cefefef',0,0,'AU','','13','');" class="avtrig user_item ">
<div class="user_item_avatar"><img class="avav acav avsex nosex " src="/avatar/default_guest.png" /> </div>
<div class="user_item_data">
<p class="username user ">cefefef</p>
</div>
</div>
<div onclick="dropUser(this,4289985,'MeowCat',0,0,'AU','','13','');" class="avtrig user_item ">
<div class="user_item_avatar"><img class="avav acav avsex nosex glob_av" src="/avatar/default_guest.png" /> </div>
<div class="user_item_data">
<p class="username user ">MeowCat</p>
</div>
</div>
</div>
<div class="clear"></div>
</div>`;
let data = [];
//let info = str.split(`'`).forEach(e => e.includes("dropUser"));
console.log(str.split(`'`));
try this:
const htmlStr = `<div id="container_user">
<div class="user_count">
<div class="bcell">
Online <span class="ucount back_theme">4</span>
</div>
</div>
<div class="online_user">
<div onclick="dropUser(this,5,'ChatAveBot',1,1,'ZZ','','0','');" class="avtrig user_item ">
<div class="user_item_avatar"><img class="avav acav avsex nosex " src="/avatar/default_avatar.png" /> </div>
<div class="user_item_data">
<p class="username user ">ChatAveBot</p>
</div>
<div class="user_item_icon icrank"><img src="default_images/rank/bot.svg" class="list_rank" title="Bot" /></div>
</div>
<div onclick="dropUser(this,3754679,'Fantastic',1,0,'ZZ','','14','');" class="avtrig user_item ">
<div class="user_item_avatar"><img class="avav acav avsex nosex " src="/avatar/avatar_user3754679_1638955491.jpg" /> </div>
<div class="user_item_data">
<p class="username bcolor1 bnfont7">Fantastic</p>
<p class="text_xsmall bustate bellips">TheDD7デイビスになる =🚮</p>
</div>
</div>
<div onclick="dropUser(this,4290052,'cefefef',0,0,'AU','','13','');" class="avtrig user_item ">
<div class="user_item_avatar"><img class="avav acav avsex nosex " src="/avatar/default_guest.png" /> </div>
<div class="user_item_data">
<p class="username user ">cefefef</p>
</div>
</div>
<div onclick="dropUser(this,4289985,'MeowCat',0,0,'AU','','13','');" class="avtrig user_item ">
<div class="user_item_avatar"><img class="avav acav avsex nosex glob_av" src="/avatar/default_guest.png" /> </div>
<div class="user_item_data">
<p class="username user ">MeowCat</p>
</div>
</div>
</div>
<div class="clear"></div>
</div>`;
function getUsers(str) {
let div = document.createElement("div");
div.innerHTML = str;
return [...div.querySelectorAll('.user_item')].map(item => {
let id = item.getAttribute('onclick').split(',')[1];
let username = item.querySelector('.username').innerHTML;
return {username, id};
})
};
console.log(getUsers(htmlStr));
I have added two new attribute to each user_item Div instade of reading from html string as text. find data-id in this html.
let str =`<div id="container_user">
<div class="user_count">
<div class="bcell">
Online <span class="ucount back_theme">4</span>
</div>
</div>
<div class="online_user">
<div onclick="dropUser(this,5,'ChatAveBot',1,1,'ZZ','','0','');" class="avtrig user_item " data-id="1" data-name="ChatAveBot">
<div class="user_item_avatar"><img class="avav acav avsex nosex " src="/avatar/default_avatar.png" /> </div>
<div class="user_item_data">
<p class="username user ">ChatAveBot</p>
</div>
<div class="user_item_icon icrank"><img src="default_images/rank/bot.svg" class="list_rank" title="Bot" /></div>
</div>
</div>
<div class="clear"></div>
</div>`;
Here is the Script to push all to in array
const Users = [];
$.each($(str).find('.user_item'), (userIndex, User) => {
let _user = {};
_user.id = $(User).attr('data-id');
_user.Name = $(User).attr('data-name');
Users.push(_user);
});
One solution I can suggest, as the original post has asked that the arguments passed to the dropUser function needs to be pushed in to an array. This solution is using regex and small string manipulations.
var regex=/dropUser\([A-Za-z0-9,'"]*\)/g;
var result=str.match(regex);
var argumentsArray = new Array();
result.forEach(input =>{ input = input.replace("dropUser(",""); input = input.replace('\)',''); argumentsArray.push(input) })
console.log(argumentsArray) //this will be a 2D array.
after this you should be able to extract the username and id, rather than reading from the .username label.

Cypress - waiters for dependent sub elelemnts

I'm stuck with problem in cypress
there is dynamic DOM:
<div class="Table">
<div class="Item">
<div class="Name"> Name1 </div>
<div class="Color"> Color1 </div>
<div class="Add"> Add </div>
</div>
<div class="Item">
<div class="Name"> Name2 </div>
<div class="Color"> Color2 </div>
<div class="Add"> Add </div>
</div>
</div>
elements .Item appear dynamically how I can wait until "Item" with
<div class="Name"> Name3 </div>
<div class="Color"> Color3 </div>
appear in this list and get .Item via Cypress
DOM before
before
<div class="Table">
<div class="Item">
<div class="Name"> Name1 </div>
<div class="Color"> Color1 </div>
<div class="Add"> Add </div>
</div>
</div>
after
<div class="Table">
<div class="Item">
<div class="Name"> Name1 </div>
<div class="Color"> Color1 </div>
<div class="Add"> Add </div>
</div>
<div class="Item">
<div class="Name"> Name1 </div>
<div class="Color"> Color2 </div>
<div class="Add"> Add </div>
</div>
</div>
or
<div class="Table">
<div class="Item">
<div class="Name"> Name1 </div>
<div class="Color"> Color1 </div>
<div class="Add"> Add </div>
</div>
<div class="Item">
<div class="Name"> Name2 </div>
<div class="Color"> Color2 </div>
<div class="Add"> Add </div>
</div>
</div>
or it could be
<div class="Table">
<div class="Item">
<div class="Name"> Name1 </div>
<div class="Color"> Color1 </div>
<div class="Add"> Add </div>
</div>
<div class="Item">
<div class="Name"> Name2 </div>
<div class="Color"> Color2 </div>
<div class="Add"> Add </div>
</div>
</div>
need to wait second row appear by Name and Color
Since class="Item" is the common factor, use a cy.get() with retry on the count of it.
cy.get('.Item').should('have.length', 2)
on npm there is a package named cypress-wait-until that should work fine
Installation
npm i -D cypress-wait-until
Import
import 'cypress-wait-until';
Usage
Refere to the official npm site

Combine two filters with javascript

Hi I created an product page with two filter - price range and checkboxes. I am able to run both filter separately, but when I tried to combine both filters, one overlaps the others. I was searching in the internet but I couldn't really find a solution. Is there a way I can filter products with two different filters The codes below are my product page and my javascript codes
product.php
// CHECKBOXES
// CHECKBOXES
var $filterCheckboxes = $('input[type="checkbox"]');
var filterFunc = function() {
var selectedFilters = {};
$filterCheckboxes.filter(':checked').each(function() {
if (!selectedFilters.hasOwnProperty(this.name)) {
selectedFilters[this.name] = [];
}
selectedFilters[this.name].push(this.value);
});
var $filteredResults = $('.productFilter');
$.each(selectedFilters, function(name, filterValues) {
$filteredResults = $filteredResults.filter(function() {
var matched = false,
currentFilterValues = $(this).data('category').split(' ');
$.each(currentFilterValues, function(_, currentFilterValue) {
if ($.inArray(currentFilterValue, filterValues) != -1) {
matched = true;
return false;
}
});
return matched;
});
});
$('.productFilter').hide().filter($filteredResults).show();
}
$filterCheckboxes.on('change', filterFunc);
// CHECKBOXES
// CHECKBOXES
// PRICE RANGE
// PRICE RANGE
$('#price_range').slider({
range:true,
min:0,
max:1000,
values:[0, 1000],
step:50,
slide: function(e, ui) {
$('#price_show').html(ui.values[0] + ' - ' + ui.values[1]);
var min = Math.floor(ui.values[0]);
$('#hidden_minimum_price').html(min + 'm');
var max = Math.floor(ui.values[1]);
$('#hidden_maximum_price').html(max + '.');
$('.productFilter').each(function() {
var minPrice = (min);
var maxPrice = (max);
var value = $(this).data('start-price');
if ((parseInt(maxPrice) >= parseInt(value) && (parseInt(minPrice) <= parseInt(value))) ){
$(this).show();
} else {
$(this).hide();
}
});
}
});
// PRICE RANGE
// PRICE RANGE
<div class="list-group">
<h3>Price</h3>
<input type="hidden" id="hidden_minimum_price" value="0" /> <!-- 'value' will not display anything - is used for function at line 191 -->
<input type="hidden" id="hidden_maximum_price" value="1000" /> <!-- 'value' will not display anything - is used for function at line 191 -->
<p id="price_show">0 - 1000</p>
<div id="price_range"></div>
</div>
<div class="list-group">
<h3>Type</h3>
<div style="height: 200px; overflow-y: auto; overflow-x: hidden;"> <!-- 'overflow-y' will create the vertical scroll effect when elements are outside the box/ 'overflow-x' will hide the horizontal elements outside the box -->
<div class="list-group-item checkbox">
<label><input type="checkbox"class="common_selector brand" value="Headphone_Speaker" id="Headphone_Speaker">Headphone & Speaker</label> <!-- 'value' is the value that will be sent to a server when a form is submitted -->
</div>
<div class="list-group-item checkbox">
<label><input type="checkbox" class="common_selector brand" value="Chair" id="Chair">Chair</label> <!-- 'value' is the value that will be sent to a server when a form is submitted -->
</div>
<div class="list-group-item checkbox">
<label><input type="checkbox" class="common_selector brand" value="Cabinet" id="Cabinet">Cabinet</label> <!-- 'value' is the value that will be sent to a server when a form is submitted -->
</div>
<div class="list-group-item checkbox">
<label><input type="checkbox" class="common_selector brand" value="Table" id="Table">Table</label> <!-- 'value' is the value that will be sent to a server when a form is submitted -->
</div>
<div class="list-group-item checkbox">
<label><input type="checkbox" class="common_selector brand" value="Box" id="Box">Box</label> <!-- 'value' is the value that will be sent to a server when a form is submitted -->
</div>
</div>
</div>
<div class="productFilter col-md-4 text-center" data-category="Headphone_Speaker" data-start-price="600">
<div class="product">
<div class="product-grid" style="background-image:url(images/product-2.jpg);">
<div class="inner">
<p>
<i class="icon-shopping-cart"></i>
<i class="icon-eye"></i>
</p>
</div>
</div>
<div class="desc">
<h3>PAVILION SPEAKER</h3>
<span class="price">$600</span>
</div>
</div>
</div>
<div class="productFilter col-md-4 text-center" data-category="Chair" data-start-price="780">
<div class="product">
<div class="product-grid" style="background-image:url(images/product-3.jpg);">
<div class="inner">
<p>
<i class="icon-shopping-cart"></i>
<i class="icon-eye"></i>
</p>
</div>
</div>
<div class="desc">
<h3>LIGOMANCER</h3>
<span class="price">$780</span>
</div>
</div>
</div>
<div class="productFilter col-md-4 text-center" data-category="Cabinet" data-start-price="800">
<div class="product">
<div class="product-grid" style="background-image:url(images/product-4.jpg);">
<div class="inner">
<p>
<i class="icon-shopping-cart"></i>
<i class="icon-eye"></i>
</p>
</div>
</div>
<div class="desc">
<h3>ALATO CABINET</h3>
<span class="price">$800</span>
</div>
</div>
</div>
<div class="productFilter col-md-4 text-center" data-category="Headphone_Speaker" data-start-price="100">
<div class="product">
<div class="product-grid" style="background-image:url(images/product-5.jpg);">
<div class="inner">
<p>
<i class="icon-shopping-cart"></i>
<i class="icon-eye"></i>
</p>
</div>
</div>
<div class="desc">
<h3>EARING WIRELESS</h3>
<span class="price">$100</span>
</div>
</div>
</div>
<div class="productFilter col-md-4 text-center" data-category="Table" data-start-price="960">
<div class="product">
<div class="product-grid" style="background-image:url(images/product-6.jpg);">
<div class="inner">
<p>
<i class="icon-shopping-cart"></i>
<i class="icon-eye"></i>
</p>
</div>
</div>
<div class="desc">
<h3>SCULPTURAL COFFEE TABLE</h3>
<span class="price">$960</span>
</div>
</div>
</div>
<div class="productFilter col-md-4 text-center" data-category="Chair" data-start-price="540">
<div class="product">
<div class="product-grid" style="background-image:url(images/product-7.jpg);">
<div class="inner">
<p>
<i class="icon-shopping-cart"></i>
<i class="icon-eye"></i>
</p>
</div>
</div>
<div class="desc">
<h3>THE WW CHAIR</h3>
<span class="price">$540</span>
</div>
</div>
</div>
<div class="productFilter col-md-4 text-center" data-category="Box" data-start-price="55">
<div class="product">
<div class="product-grid" style="background-image:url(images/product-8.jpg);">
<div class="inner">
<p>
<i class="icon-shopping-cart"></i>
<i class="icon-eye"></i>
</p>
</div>
</div>
<div class="desc">
<h3>HIMITSU MONEY BOX</h3>
<span class="price">$55</span>
</div>
</div>
</div>
<div class="productFilter col-md-4 text-center" data-category="Box" data-start-price="99">
<div class="product">
<div class="product-grid" style="background-image:url(images/product-9.jpg);">
<div class="inner">
<p>
<i class="icon-shopping-cart"></i>
<i class="icon-eye"></i>
</p>
</div>
</div>
<div class="desc">
<h3>ARIANE PRIN</h3>
<span class="price">$99</span>
</div>
</div>
</div>
<div class="productFilter col-md-4 text-center" data-category="Chair" data-start-price="350">
<div class="product">
<div class="product-grid" style="background-image:url(images/product-1.jpg);">
<div class="inner">
<p>
<i class="icon-shopping-cart"></i>
<i class="icon-eye"></i>
</p>
</div>
</div>
<div class="desc">
<h3>HAUTEVILLE CONCRETE ROCKING CHAIR</h3>
<span class="price">$350</span>
</div>
</div>
</div>
</div>
This is how my database/structure:

Getting the data id

I want to get all the id's of my left and right div for each rows and for the id's inside the div left, I want to store in array and arrange it to ascending order, and compare it to the id's of my left div. but I'm confuse how can I achieve on it.
Thank you in advance.
<div class="content">
<div class="row" id="row_0">
<div class="divider">
<div id="left">
<div data-id="310"><span data-id="310">Text here</span></div>
<div data-id="312"><span data-id="312">Text here</span></div>
<div data-id="320"><span data-id="320">Text here</span></div>
<div data-id="311"><span data-id="311">Text here</span></div>
</div>
</div>
<div class="divider">
<div id="right">
<div class="mixing"><span data-id="320"> Text</span></div>
<div class="mixing"><span data-id="310"> Text</span></div>
<div class="mixing"><span data-id="312"> Text</span></div>
<div class="mixing"><span data-id="311"> Text</span></div>
</div>
</div>
</div>
<div class="row" id="row_1">
<div class="divider">
<div id="left">
<div data-id="310"><span data-id="310">Text here</span></div>
<div data-id="312"><span data-id="312">Text here</span></div>
<div data-id="320"><span data-id="320">Text here</span></div>
<div data-id="311"><span data-id="311">Text here</span></div>
</div>
</div>
<div class="divider">
<div id="right">
<div class="mixing"><span data-id="320"> Text</span></div>
<div class="mixing"><span data-id="310"> Text</span></div>
<div class="mixing"><span data-id="312"> Text</span></div>
<div class="mixing"><span data-id="311"> Text</span></div>
</div>
</div>
</div>
<div class="btn-submit"><button id="go">Go</button></div>
</div>
<script>
$(function(){
$('#go').on('click',function(e){
$('div.content').each(function(index) {
// getting first all the id's of left div for row_0 , my code is not correct
var left_row_+index[] = $('#row_'+index).find('div#left').find('div').data('id');
// arrange the left_row_+index to Asc Order
// get the right id's store it to array , no need to arrange
// compare two array
if leftarray != rightarray
return false // exit loop immediately no further checking or continuing the loop if not equal. else console.log("Looks good");
});
});
});
</script>
You can use .map to get all values from left div then use .sort() to sort them . After sorting just use .each loop for right div then compare values of data-id and array finally print some messages.
Demo Code :
$(function() {
$('#go').on('click', function(e) {
//loop through left div
$('div.left').each(function(index) {
//get all values of left div
var itsort = $(this).find('span[data-id]').map(function() {
return $(this).data('id');
}).get();
itsort.sort(); //sort
console.log(itsort)
var flag = true;
//loop through right div
$(this).closest(".row").find(".right span[data-id]").each(function(index, value) {
//check if both have same at given position or not
if ($(this).data('id') != itsort[index]) {
console.log($(this).data('id'))
console.log("not good")
flag = false;
return false;
}
})
if (flag == true) {
console.log("All good..." + $(this).closest(".row").attr('id'))
}
});
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
<div class="row" id="row_0">
<div class="divider">
<div class="left">
<div data-id="310"><span data-id="310">Text here</span></div>
<div data-id="312"><span data-id="312">Text here</span></div>
<div data-id="320"><span data-id="320">Text here</span></div>
<div data-id="311"><span data-id="311">Text here</span></div>
</div>
</div>
<div class="divider">
<div class="right">
<div class="mixing"><span data-id="320"> Text</span></div>
<div class="mixing"><span data-id="310"> Text</span></div>
<div class="mixing"><span data-id="312"> Text</span></div>
<div class="mixing"><span data-id="311"> Text</span></div>
</div>
</div>
</div>
<div class="row" id="row_1">
<div class="divider">
<div class="left">
<div data-id="310"><span data-id="310">Text here</span></div>
<div data-id="312"><span data-id="312">Text here</span></div>
<div data-id="320"><span data-id="320">Text here</span></div>
<div data-id="311"><span data-id="311">Text here</span></div>
</div>
</div>
<div class="divider">
<div class="right">
<div class="mixing"><span data-id="310"> Text</span></div>
<div class="mixing"><span data-id="311"> Text</span></div>
<div class="mixing"><span data-id="312"> Text</span></div>
<div class="mixing"><span data-id="320"> Text</span></div>
</div>
</div>
</div>
<div class="btn-submit"><button id="go">Go</button></div>
</div>

jQuery - ordering divs in ascending order

So I have this code
var $divs = $("div.product");
$('#priceAscending').on('click', function() {
var ascendingOrderedDivs = $divs.sort(function(a, b) {
return $(a).find("div.price").text() > $(b).find("div.price").text();
});
$("#container").html(ascendingOrderedDivs);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap">
<button id="priceAscending">Price ascending</button>
<!--<button id="priceDescending">Price descending</button>-->
<div id="container">
<div class="product">
<span id="name">Product One</span>
<div class="price">14.85$</div>
</div>
<div class="product">
<span id="name">Product Two</span>
<div class="price">27.59$</div>
</div>
<div class="product">
<span id="name">Product Three</span>
<div class="price">2.64$</div>
</div>
</div>
</div>
I want to sort div.product in ascending order based on the price, but it doesn't work. It puts 2.64 in the middle but it should put it first.
How can I fix this issue using jQuery?
You need to change > to -
return $(a).find("div.price").text() - $(b).find("div.price").text();
You also need to remove $ from price to compare the values. You can do it with str.slice(0, -1)
return $(a).find("div.price").text().slice(0, -1) - $(b).find("div.price").text().slice(0, -1);
Here is a working JSFiddle
I suggest using the numeric value instead of the string
var divs = $("div.product");
$('#priceAscending').on('click', function() {
var ascendingOrderedDivs = divs.sort(function(a, b) {
var aVal = parseFloat($(a).find("div.price").text().replace("$",""));
var bVal = parseFloat($(b).find("div.price").text().replace("$",""));
return aVal - bVal;
});
$("#container").html(ascendingOrderedDivs);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap">
<button id="priceAscending">Price ascending</button>
<!--<button id="priceDescending">Price descending</button>-->
<div id="container">
<div class="product">
<span id="name">Product One</span>
<div class="price">14.85$</div>
</div>
<div class="product">
<span id="name">Product Two</span>
<div class="price">27.59$</div>
</div>
<div class="product">
<span id="name">Product Three</span>
<div class="price">2.64$</div>
</div>
</div>
</div>
You could replace the $ at the end of the prices with an empty string and use parseFloat to compare the values. Note that id's on the page should be unique. For all the spans you use id="name
var $divs = $("div.product");
$('#priceAscending').on('click', function() {
var ascendingOrderedDivs = $divs.sort(function(a, b) {
return parseFloat($(a).find("div.price").text().replace(/\$$/, '')) - parseFloat($(b).find("div.price").text().replace(/\$$/, ''));
});
$("#container").html(ascendingOrderedDivs);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap">
<button id="priceAscending">Price ascending</button>
<!--<button id="priceDescending">Price descending</button>-->
<div id="container">
<div class="product">
<span id="name">Product One</span>
<div class="price">14.85$</div>
</div>
<div class="product">
<span id="name">Product Two</span>
<div class="price">27.59$</div>
</div>
<div class="product">
<span id="name">Product Three</span>
<div class="price">2.64$</div>
</div>
</div>
</div>

Categories

Resources