Jquery sort div based on multiple conditions - javascript

I have this short bit of code to sort / ascend div by number. But I want to add other conditions to sort by. Right now, it's only sorting it just based on points class. But I want it to also apply conditions on times and combine with points.
Generally these divs sort ascend from large number to low number. If the number is equal, it will show those whose time is less. If the number is equal, it will search to see which times is the lowest. And it will show it First.
$(function(){
var sortedList = $('.contest_entry').toArray().sort(function(lhs, rhs){
return parseInt($(rhs).children("span.points").text(),10) - parseInt($(lhs).children("span.points").text(),10);
});
$("#list").html(sortedList);
});
.contest_entry
{
padding:10px;
background: #eee;
margin:10px 0px;
}
.points
{
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div id="list">
<div class="contest_entry">
<span class="points">14</span>
<span class="times"> 12:39 </span>
</div>
<div class="contest_entry">
<span class="points">16</span>
<span class="times"> 09:55 </span>
</div>
<div class="contest_entry">
<span class="points">19</span>
<span class="times"> 17:19 </span>
</div>
<div class="contest_entry">
<span class="points">19</span>
<span class="times"> 17:34 </span>
</div>
<div class="contest_entry">
<span class="points">19</span>
<span class="times"> 17:20 </span>
</div>
</div>
In summary, I want to add multiple conditions to filter or sort the divs.

Try this code please
$(function(){
var sortedList = $('.contest_entry').toArray().sort(function(lhs, rhs){
var lhsPoints = parseInt($(lhs).find(".child span.points").text(),10);
var rhsPoints = parseInt($(rhs).find(".child span.points").text(),10);
if (lhsPoints === rhsPoints) {
// Compare the "times" class if the "points" class is equal
return $(lhs).find(".child span.times").text() > $(rhs).find(".child span.times").text() ? 1 : -1;
} else {
return rhsPoints - lhsPoints;
}
});
$("#list").html(sortedList);
});

Try this script please
$(function(){
var sortedList = $('.contest_entry').toArray().sort(function(lhs, rhs){
var lhsPoints = parseInt($(lhs).children("span.points").text(),10);
var rhsPoints = parseInt($(rhs).children("span.points").text(),10);
if (lhsPoints === rhsPoints) {
// Compare the "times" class if the "points" class is equal
return $(lhs).children("span.times").text() > $(rhs).children("span.times").text() ? 1 : -1;
} else {
return rhsPoints - lhsPoints;
}
});
$("#list").html(sortedList);
});

Related

How to get grand total of all input values in javascript if dynamically entered

I'm looking to acquire a grand total of all product input field values that are dynamically generated when a user clicks on either the plus or minus button which, for that, adds the total price for each product.
Any help is greatly appreciated. This is what I have so far:
JS
$(function() {
$('.service_product-item').each(function() {
var thisEl = $(this),
btnPlus = thisEl.find('.service_btn-plus'),
btnMinus = thisEl.find('.service_btn-minus'),
fieldQtt = thisEl.find('input[name="service-qt1"],input[name="service-qt2"]'),
itemPriceEl = thisEl.find('.service_item-price'),
price = itemPriceEl.data('price');
// Add Products & Products Price
btnPlus.on('click', function() {
qttValue = parseInt(fieldQtt.val());
fieldQtt.val(qttValue + 1);
itemPriceEl.html('$' + (qttValue + 1) * price);
});
// Subtract Products & Products Price
btnMinus.on('click', function() {
qttValue = parseInt(fieldQtt.val()) - 1;
var newQTT = (qttValue <= 0) ? 0 : qttValue;
fieldQtt.val(newQTT);
itemPriceEl.html('$' + newQTT * price);
});
});
});
HTML
<div class="service_products_and_services_wrapper">
<div class="service_product-items">
<div class="service_product-item">
<div class="service_item-wrap">
<img src="http://www.kinyu-z.net/data/wallpapers/27/796765.png" alt="QT1" title="" />
<div class="service_wrap-qtt">
<div class="service_wrap-qtt-field-qtt">
<input class="service_field-qtt" name="service-qt1" value="0" readonly="" />
</div>
<div class="service_wrap-qtt-minus-plus">
<div class="service_btn-cart-qtt service_btn-plus">+</div>
<div class="service_btn-cart-qtt service_btn-minus">-</div>
</div>
</div>
</div>
<div class="service_item-info">
<div class="service_item-title">QT1<br>
<span style="font-size: .7em; text-transform: none;">($5 per item)</span>
</div>
<div class="service_item-price" data-price="5">$0</div>
</div>
</div>
<div class="service_product-item">
<div class="service_item-wrap">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRIuVn6ZXHwQiFC0IlB1N_CxbXo6-5x1A4yqspYsxUUb0Xjmu8L" alt="QT2" title="" />
<div class="service_wrap-qtt">
<div class="service_wrap-qtt-field-qtt">
<input class="service_field-qtt" name="service-qt2" value="0" readonly="" />
</div>
<div class="service_wrap-qtt-minus-plus">
<div class="service_btn-cart-qtt service_btn-plus">+</div>
<div class="service_btn-cart-qtt service_btn-minus">-</div>
</div>
</div>
</div>
<div class="service_item-info">
<div class="service_item-title">QT2<br>
<span style="font-size: .7em; text-transform: none;">($10 per item)</span>
</div>
<div class="service_item-price" data-price="10">$0</div>
</div>
</div>
</div>
<p style="margin-top: 40px;">Grand Total: $0</p>
</div>
and here is a DEMO
There are some issues with the problem statement. Main one is that you don't really have any model defined for your application and your html acts as a data model as well, and important data is scoped to the event handlers. Also it is not clear what is the initial state of that application. So I just modify your code a bit.
One simple approach just to show how it could be done is following:
have a global total
with each minus and plus update the value accordingly
https://jsfiddle.net/Lyxceu3s/43/
var total = 0;
$(function() {
$('.service_product-item').each(function() {
var thisEl = $(this),
btnPlus = thisEl.find('.service_btn-plus'),
btnMinus = thisEl.find('.service_btn-minus'),
fieldQtt = thisEl.find('input[name="service-qt1"],input[name="service-qt2"]'),
itemPriceEl = thisEl.find('.service_item-price'),
price = itemPriceEl.data('price');
// Add Products & Products Price
btnPlus.on('click', function() {
qttValue = parseInt(fieldQtt.val());
fieldQtt.val(qttValue + 1);
total = total + price;
itemPriceEl.html('$' + (qttValue + 1) * price);
$('#idGT').html(total);
});
// Subtract Products & Products Price
btnMinus.on('click', function() {
qttValue = parseInt(fieldQtt.val()) - 1;
if(qttValue >= 0){
total = total - price;
}
var newQTT = (qttValue <= 0) ? 0 : qttValue;
fieldQtt.val(newQTT);
itemPriceEl.html('$' + newQTT * price);
$('#idGT').html(total);
});
});
});
And that would also require a little modification to your html:
<p style="margin-top: 40px;">Grand Total: $<span id="idGT">0</span></p>
Note: that in case of a minus, you have to check that quantity is above or 0 before you conditionally reset it to 0.
As a general note, you might want to separate your models from your views. Check the following SO thread for a digest: "Hello World" in MVC Pattern
Updated the fiddle. Made few changes to it
Please take a look at it and let me know if thats what you are looking for.
https://jsfiddle.net/Lyxceu3s/35/
var firstTotal = $('input[name="service-qt2"]').val() * 10 ;
var secondTotal = $('input[name="service-qt1"]').val() * 5;
$('#grandTotal').html(firstTotal + secondTotal)

how to expand and collapse a mixed list of shown and hidden elements (filtered divs) without showing the hidden ones

I'm basically new to coding but i have this LONG list of products which i need to filter according to certain criteria plus a show more/less function. The issues are: 1. When i filter elements, some categories have less items than the default set, 2. if the shown element's total height is is shorter i need the container's height to match that height (i set a max-height but then it won't increase when the filter changes the number of products or i try to expand the list to show other hidden products) 3. if a filter is applied and the list is longer than the default lenght shown, if i use the function to show more items, the hidden elements that do not belong to that category become visible.
Here is the actual jquery script, the html is so long i'm not posting it complete, but i'll post an example of the product setup.
jQuery script
$(document).ready(function() {
var productList = $("#product_list:nth-child(3n+1):visible").height(); /*$("#product_list:nth-child(3n+1):visible").each(function(){productList += $(this).height();});*/
var counter = 0;
//filter functions
$("ul#filters li a.button").click(function() {
$("ul#filters li a.button").removeClass("active");
$(this).addClass("active");
if ($(this).hasClass("active") == true) {
var act = $(this).attr("id");
$(".product:not(#" + act + ")").fadeOut(800);
$(".product#" + act + "").fadeIn(800);
$(".products .product:nth-child(4n+1)").css("border-left-width", 0);
$("#product_list:last-child:visible").css("border-right", "2px dashed #008140");
if (act == "all") {
$(".product").fadeIn(800);
} else {
if ($(".product:last:visible") >= $(".product:last")) {
//$("#loadmore").css("display", "none");
$(".product:last:visible").css("border-right", "2px dashed #008140");
}
}
}
});
//show more -show less
$("#loadmore").click(function showNext() {
$("#product_list").animate({
height: productList + 3000
}, 800);
$(".product:hidden:lt(20)").slideDown();
$("#showless").css("display", "block");
counter = counter + 20;
productList = productList + 3000;
if ($(".product:last").is(":visible")) {
$("#product_list").css("max-height", (productList - 2300));
$("#product_list:last-child:visible").css("border-right", "2px dashed #008140");
$("#loadmore").css("display", "none");
}
if ($("."))
});
$("#showless").click(function showLess() {
//$(".product:visible:gt("+(counter-1)+")").slideUp()
$("#product_list").animate({
height: productList - 3000
}, 800);
counter = counter - 20;
productList = productList - 3000;
if (productList == 3000) {
$("#showless").css("display", "none");
}
if ($("#loadmore").css("display", "none")) {
$("#loadmore").css("display", "block");
}
});
});
product HTML
<div class="container">
<!-- Row -->
<div class="row" id="product_list">
<!-- Product -->
<div class="col-xs-6 col-sm-3 product" id="belleza">
<!-- Entry -->
<div class="entry">
<figure class="entry-thumbnail">
<img alt="" src="../resources/images/productos/Shampoo-neutro.png"/>
</figure>
<div class="entry-body">
<h3 class="entry-title">
Shampoo Petra Neutro<br/>
</h3>
<h2 class="entry-title">
<select id="presentaciones">
<option id="shampoo-neutro260">Frasco Dosificador x260ml</option>
</select>
</h2>
<h2 class="entry-title" id="disponible">Disponibles: <span class="unidades" id="shampoo-neutro">10</span>
</h2>
<span class="price"><ins><span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">$</span>12.00</span></ins>
<del><span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">$</span>15.00</span></del></span>
<div class="buttons">
<a class="button add_to_cart_button" rel="nofollow">Add to cart</a>
</div>
</div>
</div>
<!-- End Entry -->
</div>
<!--End Col -->
</div>
</div>

jQuery increase value only at clicked div

I need to increase value, by clicking plus or minus picture. It works fine when it's only one "item_quantity" block at the page. But it works incorrectly if I wanna add another "item_quantity" block.
JS code that increase value:
$('.item_quantity .plus').click(function() {
var num = parseInt($('.item_quantity .quan_numb').text());
$('.item_quantity .quan_numb').text(num + 1);
});
http://codepen.io/Vlasov/pen/dvogmp?editors=1010
$(this).parent().find('.quan_numb')
http://codepen.io/anon/pen/ZeGqmd?editors=1010
$('.item_quantity .plus').click(function() {
var num = parseInt($(this).parent().find('.quan_numb').html());
$(this).parent().find('.quan_numb').html(num + 1);
});
$('.item_quantity .minus').click(function() {
var num = parseInt($(this).parent().find('.quan_numb').html());
if (num > 1) {
$(this).parent().find('.quan_numb').html(num - 1);
}
});
.minus img, .plus img{
width: 20px;
cursor: pointer;
}
.quan_numb{
font-size: 24px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item_quantity fll">
<span class="minus">
<img src="http://www.sammy-icon.com/catalog/view/theme/default/image/icon/minus.png" alt="">
</span>
<span class="quan_numb">1</span>
<span class="plus">
<img src="http://www.sammy-icon.com/catalog/view/theme/default/image/icon/plus.png" alt="">
</span>
</div>
<div class="item_quantity fll">
<span class="minus">
<img src="http://www.sammy-icon.com/catalog/view/theme/default/image/icon/minus.png" alt="">
</span>
<span class="quan_numb">1</span>
<span class="plus">
<img src="http://www.sammy-icon.com/catalog/view/theme/default/image/icon/plus.png" alt="">
</span>
</div>
Try this :
$('.item_quantity .plus').click(function() {
var num = parseInt($(this).siblings('.item_quantity .quan_numb').text());
$(this).siblings('.item_quantity .quan_numb').text(num + 1);
});
$('.item_quantity .minus').click(function() {
var num = parseInt($(this).siblings('.item_quantity .quan_numb').text());
if (num > 1) {
$(this).siblings('.item_quantity .quan_numb').text(num - 1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item_quantity fll">
<span class="minus">
<img src="http://www.sammy-icon.com/catalog/view/theme/default/image/icon/minus.png" alt="">
</span>
<span class="quan_numb">1</span>
<span class="plus">
<img src="http://www.sammy-icon.com/catalog/view/theme/default/image/icon/plus.png" alt="">
</span>
</div>
<div class="item_quantity fll">
<span class="minus">
<img src="http://www.sammy-icon.com/catalog/view/theme/default/image/icon/minus.png" alt="">
</span>
<span class="quan_numb">1</span>
<span class="plus">
<img src="http://www.sammy-icon.com/catalog/view/theme/default/image/icon/plus.png" alt="">
</span>
</div>
You are using the class selector for selecting the quantities.
You need to be a touch more specific, and reference each individual quantity.
You can find the closest .quan_numb by performing:
var quan_numb = $(this).closest(".item_quantity").find(".quan_numb");
Which finds the closest parent with class item_quantity, then finds the child quan_num.
codepen
It work incorrect because you are using Class use Id instead of class
$('#item_quantity1 .plus').click(function() {
var num = parseInt($('#item_quantity1 .quan_numb').text());
$('#item_quantity1 .quan_numb').text(num + 1);
});
If you want to add more use different Id's
It because jQuery will return an array if the selector belongs to multiple elements. Use the following code to specify the element that is paired with the button.
var num = parseInt($(this).siblings('.quan_numb').text());
See on Codepen

Calculate percent of each element

I've the following code to calculate the percentage of each element (like poll voting system):
$(document).ready(function() {
$("#percentage").click(function() {
var number, sumNumbers = 0, newPercent;
$(".item").each(function() {
number = $(this).children(".itemNum").text();
number = +number;
sumNumbers += number;
if(sumNumbers != 0) {
newPercent = (number / sumNumbers) * 100;
} else {
newPercent = 0;
}
$(this).children(".percentage").text(newPercent+"%");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">
<span class="itemNum">0</span> <span class="percentage"></span>
</div>
<div class="item">
<span class="itemNum">2</span> <span class="percentage"></span>
</div>
<div class="item">
<span class="itemNum">1</span> <span class="percentage"></span>
</div>
<button id="percentage">Calculate Percentage!</button>
But, the result is:
0 0%
2 100%
1 33.33333333333333%
So, how to calculate return the following result?
0 0%
2 66.66666666666667%
1 33.33333333333333%
I need these results to do a progress bar on my poll system, so, how to do this?
You need to parse the text to integer via parseInt() function.
And you need first to sum numbers and then you can calculate percentage.
For one loop question:
You can't count percentage in one loop. Explained here
$(document).ready(function() {
$("#percentage").click(function() {
var number, sumNumbers = 0, newPercent;
$(".item").each(function(){
number = $(this).children(".itemNum").text();
sumNumbers += parseInt(number);
});
$(".item").each(function() {
number = parseInt($(this).children(".itemNum").text());
if(sumNumbers != 0) {
newPercent = (number / sumNumbers) * 100;
} else {
newPercent = 0;
}
$(this).children(".percentage").text(newPercent+"%");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">
<span class="itemNum">0</span> <span class="percentage"></span>
</div>
<div class="item">
<span class="itemNum">2</span> <span class="percentage"></span>
</div>
<div class="item">
<span class="itemNum">1</span> <span class="percentage"></span>
</div>
<button id="percentage">Calculate Percentage!</button>

If statement from span "1 left"?

I need to create an if statement in Js fetching when there's only 1 left (product) in stock. How would I go about this?
HTML on productpage:
<div id="product-spec">
<div class="row">
<ul class="col-xs-12">
<li class="h4">
<span class="availabilty"
<span class="small">1 left</span>
</span>
</li>
</ul>
</div>
</div>
My Javascript so far:
if (.small == 1 left) {
// execute this code
}
W3 Schools - If Statements doesn't make me more sane.
try
if(document.querySelectorAll(".small")[0].innerHTML==="1 left"){
// get funky
}
[EDIT]
if($(".small").eq(0).text() == "1 left"){
$(".small").eq(0).prepend( "<div style="lots of styling"></div>" );
}
You write like this
var product = document.getElementsByClassName('modal_link')[0];
// if inner text exist
if(product.innerText) {
// getting count products from string
var countProduct = parseInt(product.innerText, 10);
if(countProduct === 1) {
console.log('Left');
}
}

Categories