How to select values from li elements in Cheerio/jQuery? - javascript

<div class="tabs__content tabs__content--bg js-tab-panel">
<div class="tabs__panel tabs__panel--active">
<div class="product__sizes-wrapper">
<ul class="product__sizes-select js-size-select-list" data-locale="UK">
<li class="product__sizes-option" data-msg="Sample Message" data-name="6" data-value="060">
<span class="product__sizes-size">
<span class="product__sizes-size-1">6</span>
<span class="product__sizes-size-2"></span>
</span>
</li>
<li class="product__sizes-option" data-msg="Sample Message" data-name="7" data-value="070">
<span class="product__sizes-size">
<span class="product__sizes-size-1">7</span>
<span class="product__sizes-size-2"></span>
</span>
</li>
<li class="product__sizes-option" data-msg="Sample Message" data-name="8" data-value="080">
<span class="product__sizes-size">
<span class="product__sizes-size-1">8</span>
<span class="product__sizes-size-2"></span>
</span>
</li>
<li class="product__sizes-option" data-msg="Sample Message" data-name="9.5" data-value="095">
<span class="product__sizes-size">
<span class="product__sizes-size-1">9.5</span>
<span class="product__sizes-size-2"></span>
</span>
</li>
</ul>
</div>
</div>
I want to extract the values from the product__sizes-size-1 classes and transform them into an array. I have tried to use a .map() function to try and populate an array but it appears empty. To make it clear I want to have the array populated like [6,7,8,9.5] etc...
const sizes = $(".product__sizes-wrapper [data-locale = 'UK']").map(function() {
return $(this).text();
}).get();

Your approach is correct, you just use the wrong selector. Use product__sizes-size-1 instead:
$(document).ready(function(){
var sizes = $('.product__sizes-size-1').map(function(){return $(this).text()}).get();
});

To select it
$('#product__sizes-select li.product__sizes-size-1');
In array
var product_sizes = [];
$('ul').each(function() {
var localproduct_sizes = [];
$(this).find('li').each(function(){
localproduct_sizes.push( $(this).attr('product__sizes-size-1') );
});
product_sizes.push(localproduct_sizes);
});

Related

Getting highest score values from firebase database

In my website there are some films that i get from firebase. The scores of the movies are between 0 and 100. I already got all the movies in my website. I also want to display them in descending order.(for ex. top 5 rated movies) How can i achieve this? Thanks for your answers.
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
const auth = getAuth(app);
const firebaseRef= ref(getDatabase());
var body = document.getElementById('movies');
var body2 = document.getElementById('series');
function AddItemsToTable(name, score, img, id) {
var movies = `<div class="content"><img src="${img}" ><p>${name}</p> <p> <i class="fa fa-star checked" id="star${id}"></i> <a class="scoretxt">${score}%</a> </p> </div>`;
body.innerHTML+=movies;
}
function AddItemsToTable2(name, score, img, id) {
var series = `<div class="content"><img src="${img}" ><p>${name}</p> <p> <i class="fa fa-star checked" id="star2${id}"></i> <a class="scoretxt">${score}%</a> </p> </div>`;
body2.innerHTML += series;
}
//*******************************I got the movies************************************************
function AddAllItemsToTable(TheMovies){
var counter=0;
TheMovies.forEach(element => {
if (counter===6) {
return;
}
AddItemsToTable(element.movieName, element.movieScore, element.movieImage, element.movieId);
counter++;
});
}
//************************I got tv series*********************************************
function AddAllItemsToTable2(TheSeries){
var counter=0;
TheSeries.forEach(element => {
if (counter===6) {
return;
}
AddItemsToTable2(element.seriesName, element.seriesScore, element.seriesImage, element.seriesId);
counter++;
});
}
function AddAllItemsToTable3(TheMovies){
var counter=0;
TheMovies.forEach(element => {
if (counter===6) {
return;
}
AddItemsToTable3(element.movieName, element.movieScore, element.movieImage, element.movieId);
counter++;
});
}
function getAllDataOnce(){
const dbRef=ref(db);
get(child(dbRef,"Movies"))
.then((snapshot)=>{
var movies=[];
snapshot.forEach(childSnapshot => {
movies.push(childSnapshot.val())
});
AddAllItemsToTable(movies);
});
}
function getAllDataOnce2(){
const dbRef=ref(db);
get(child(dbRef,"Series"))
.then((snapshot)=>{
var series=[];
snapshot.forEach(childSnapshot => {
series.push(childSnapshot.val())
});
AddAllItemsToTable2(series);
});
}
window.onload = (event) => {
getAllDataOnce();
getAllDataOnce2();
};
<div class="grid-container">
<header class="header">
<div class="solheader">
<img src="img/sonlogo3.png" alt="logo">
<img src="img/logosmall.png" alt="logo" style="width:60px;height:48px;margin:5px;">
</div>
<div class="ortaheader">
<input type="text" placeholder="Movies or TV series.." class="searchbox"><i class="fa fa-search arama"></i> </input>
<ul>
<li class="categories">Categories <i class="fa fa-caret-down" style="font-size:16px;"> </i>
<ul class="dropdown">
<li>TV Series</li>
<li>Movies</li>
</ul>
</li>
</ul>
</div>
<div class="menu sagheader">
<ul>
<li>
<button class="ikon dropdown-toggle" type="button" data-toggle="dropdown"><i class="far fa-user"></i> </button>
<ul class="dropdown-menu">
<li class="accountname"><b><script>document.write(document.cookie.substring(5))</script></b></li>
<li class="login"><i class="fa fa-sign-in-alt" style="color:red;"></i> Login </li>
<li class="signup"><i class="fa fa-user-plus" style="color:red;"></i> Sign up </li>
<li class="logout"><a onclick="deletecookie()" style="cursor:pointer;"><i class="fas fa-door-open" style="color:red;"></i> Log out</a></li>
</ul>
</li>
</ul>
</div>
</header>
<div class="body" id="body">
<div class="baslik">Movies</div>
<div class="baslik2">See all</div>
<div id="movies">
</div>
<div class="baslik">Series</div>
<div class="baslik2">See all</div>
<div id="series">
</div>
<div class="baslik">Top Rated Movies</div>
<div class="baslik2">See all</div>
<div id="toprated">
</div>
</div>
<div class="footer">
<div class="">
<img src="img/sonlogo3.png" alt="logo">
<ul>
<li>Help</li>
<li>About</li>
<li>Contact</li>
<li>Terms and Policies</li>
</ul><br><br>
<ul>
<li>© 2021 Cinemeter</li>
<li class="destroy">|</li>
<li>All rights reserved.</li>
</ul>
</div>
</div>
</div>
Firebase Database
This is my website
While Firebase can order results, the results are always ascending. If you want to show them in descending order, you'll have to reverse them in your application code.
Something like this:
const query = query(child(dbRef,"Movies"), orderByChild("movieScore"));
get(query).then((snapshot)=>{
var movies=[];
snapshot.forEach(childSnapshot => {
movies.push(childSnapshot.val())
});
movies.reverse
});
If you want to get the top scores, you can use limitToLast in the query too:
const query = query(child(dbRef,"Movies"), orderByChild("movieScore"), limitToLast(5));
Also see the Firebase documentation on ordering and filtering data and limiting the number of results.
A few notes on your data structure:
Using sequential numeric keys for you nodes is an anti-pattern in Firebase, and it is typically better to use push keys. Also see Best Practices: Arrays in Firebase.
You're storing the score as a string, which is bound to lead to problems as strings are sorted lexicographically. I recommend converting your data to store the scores as numbers (so without " quotes around them).

Add class in loop attribute with javascript

I want to put a class in multiple attributes if it's in the correct url.
I am entering the case if it is in url and trying to add, the code in the console just says undefined but does not perform the actions.
document.addEventListener('DOMContentLoaded', () => {
for (var i = 0; i < 40; i++) {
document.querySelector('span .price').classList.add("forcehide");
}
});
span.price.forcehide {
display: none;
}
<div class="info-details">
<strong class="product name product-item-name">
<a class="product-item-link" href="https://www.myurl.com.br/product"> NAme Product </a>
</strong>
<div class="price-box price-final_price" data-role="priceBox" data-product-id="2293" data-price-box="product-id-2293">
<span class="price-container price-final_price tax weee">
<span id="product-price-2293" data-price-amount="13.9" data-price-type="finalPrice" class="price-wrapper ">
<span class="price">R$13,90</span>
</span>
</span>
</div>
</div>
<div class="info-details">
<strong class="product name product-item-name">
<a class="product-item-link" href="https://www.myurl.com.br/product"> NAme Product </a>
</strong>
<div class="price-box price-final_price" data-role="priceBox" data-product-id="2293" data-price-box="product-id-2293">
<span class="price-container price-final_price tax weee">
<span id="product-price-2293" data-price-amount="13.9" data-price-type="finalPrice" class="price-wrapper ">
<span class="price">R$13,90</span>
</span>
</span>
</div>
</div>
How to delete all price?
As Satpal said in the comments, querySelector method returns just one element.
To get a list of all elements matching the query selector, you should use querySelectorAll:
document.addEventListener("DOMContentLoaded", () => {
const spans = document.querySelectorAll("span.price");
for (let i = 0; i < spans.length; i++) {
const span = spans[i];
span.classList.add("forcehide");
}
});
document.addEventListener("DOMContentLoaded", () => {
const spans = document.querySelectorAll("span.price");
for (let i = 0; i < spans.length; i++) {
const span = spans[i];
span.classList.add("forcehide");
}
});
span.price.forcehide {
display: none;
}
<div class="info-details">
<strong class="product name product-item-name">
<a class="product-item-link" href="https://www.myurl.com.br/product"> NAme Product </a>
</strong>
<div class="price-box price-final_price" data-role="priceBox" data-product-id="2293" data-price-box="product-id-2293">
<span class="price-container price-final_price tax weee">
<span id="product-price-2293" data-price-amount="13.9" data-price-type="finalPrice" class="price-wrapper ">
<span class="price">R$13,90</span>
</span>
</span>
</div>
</div>
<div class="info-details">
<strong class="product name product-item-name">
<a class="product-item-link" href="https://www.myurl.com.br/product"> NAme Product </a>
</strong>
<div class="price-box price-final_price" data-role="priceBox" data-product-id="2293" data-price-box="product-id-2293">
<span class="price-container price-final_price tax weee">
<span id="product-price-2293" data-price-amount="13.9" data-price-type="finalPrice" class="price-wrapper ">
<span class="price">R$13,90</span>
</span>
</span>
</div>
</div>

MVC javascript display selected data

First of all, I list the e-mail from coming ActionResult in the first cycle.
I want to see the details by clicking on the listed data. I open with the help of jQuery details. The problem arises in this section. in this case ,the opening of the details of the first mail in the detail of each row.
There are details of the message in the second loop.To connect to the two loops in a guid font was coming. (MessageId).
id=messageId (guid type)
mailing list
<div class="message-list-container">
<div class="message-list" id="message-list">
#foreach (var item in Model)
{
<div id="#item.MessageId" class="message-item">
<span class="sender" title="#item.From">
#item.From
</span>
<span class="time">#mvcHelper.saatAyarla(item.Date)</span>
#if(item.Attachments.Any())
{
<span class="attachment">
<i class="ace-icon fa fa-paperclip"></i>
</span>
}
<span class="summary">
<span class="text">
#item.Subject
</span>
</span>
</div>
}
</div>
</div>
mailing details
<!--Messsage details-->
#foreach (var item in Model)
{
<!-- <div class="hide message-content" id="id-message-content">-->
<div class="hide message-content" id="#item.MessageId">
<div class="message-header clearfix">
<div class="pull-left">
<span class="blue bigger-125"> #item.Subject </span>
<div class="space-4"></div>
<i class="ace-icon fa fa-star orange2"></i>
<img class="middle" alt="John's Avatar" src="/Areas/admin/Content/images/avatars/avatar.png" width="32" />
#item.From
<i class="ace-icon fa fa-clock-o bigger-110 orange middle"></i>
<span class="time grey">#mvcHelper.saatGoster(item.Date)</span>
</div>
</div>
<div class="hr hr-double"></div>
<div class="message-body">
<p>
#item.TextBody
</p>
</div>
<div class="hr hr-double"></div>
<!--Eklenti paneli-->
<div class="message-attachment clearfix">
#if (item.Attachments.Any())
{
<div class="attachment-title">
<span class="blue bolder bigger-110">Eklentiler</span>
<span class="grey">(#item.Attachments.Count() Dosya)</span>
</div>
<ul class="attachment-list pull-left list-unstyled">
#foreach (var attachment in item.Attachments)
{
<li>
<a href="#" class="attached-file">
<i class="ace-icon fa fa-file-o bigger-110"></i>
<span class="attached-name">#mvcHelper.getAttachmentName(attachment.ToString())</span>
</a>
<span class="action-buttons">
<a href="#">
<i class="ace-icon fa fa-download bigger-125 blue"></i>
</a>
<a href="#">
<i class="ace-icon fa fa-trash-o bigger-125 red"></i>
</a>
</span>
</li>
}
</ul>
}
</div>
</div><!-- /.message-content -->
}
<!--Eklenti paneli Son-->
<!--message details end-->
loop connecting two points.
first foreach = <div id="#item.MessageId" class="message-item">
//Places where the problem is. They need to be connected.
second foreach = <!-- <div class="hide message-content" id="id-message-content">-->
<div class="hide message-content" id="#item.MessageId">
var content = message.find('.message-content:last').html($('#id-message-content').html());
jQuery code
$('.message-list .message-item .text').on('click', function () {
var message = $(this).closest('.message-item');
//if message is open, then close it
if (message.hasClass('message-inline-open')) {
message.removeClass('message-inline-open').find('.message-content').remove();
return;
}
$('.message-container').append('<div class="message-loading-overlay"><i class="fa-spin ace-icon fa fa-spinner orange2 bigger-160"></i></div>');
setTimeout(function () {
$('.message-container').find('.message-loading-overlay').remove();
message
.addClass('message-inline-open')
.append('<div class="message-content" />');
var content = message.find('.message-content:last').html($('#id-message-content').html());
//remove scrollbar elements
content.find('.scroll-track').remove();
content.find('.scroll-content').children().unwrap();
content.find('.message-body').ace_scroll({
size: 150,
mouseWheelLock: true,
styleClass: 'scroll-visible'
});
}, 500 + parseInt(Math.random() * 500));
});
Your first problem is that you are creating multiple elements with identical id properties. This makes your HTML invalid.
Here is the problem code:
#foreach (var item in Model)
{
<div id="#item.MessageId" class="message-item">
...
#foreach (var item in Model)
{
<div class="hide message-content" id="#item.MessageId">
...
For each message in your model, this will create 2 <div> elements whose id has the value of the #item.MessageID variable. The second of these is and illegal element because it has the same ID as an earlier element. You will need to make these <div>s have unique IDs.
The second problem is:
When you run
var content = message.find('.message-content:last').html($('#id-message-content').html());
this part:
$('#id-message-content').html()
cannot find anything because there is no element whose id is "id-message-content". Also every time you open the message, you are appending another "message-content" div into the message-item. This is not necessary.
To fix these issues, you can change the code like this:
First loop:
#foreach (var item in Model)
{
<div data-messageid="#item.MessageId" class="message-item">
...
<span class="summary">
<span class="text">
#item.Subject
</span>
</span>
<div class="message-content" hidden></div>
...
Second loop:
#foreach (var item in Model)
{
<div class="hide message-content" id="message-content-#item.MessageId">
...
jQuery:
$('.message-list .message-item .text').on('click', function () {
var message = $(this).parents('.message-item');
//if message is open, then close it
if (message.hasClass('message-inline-open')) {
message.removeClass('message-inline-open').find('.message-content').hide();
return;
}
$('.message-container').append('<div class="message-loading-overlay"><i class="fa-spin ace-icon fa fa-spinner orange2 bigger-160"></i></div>');
setTimeout(function () {
$('.message-container').find('.message-loading-overlay').remove();
message.addClass('message-inline-open');
var content = message.find(".message-content");
content.show();
content.html($('#message-content-' + message.data("messageid")).html());
//remove scrollbar elements
content.find('.scroll-track').remove();
content.find('.scroll-content').children().unwrap();
content.find('.message-body').ace_scroll({
size: 150,
mouseWheelLock: true,
styleClass: 'scroll-visible'
});
}, 500 + parseInt(Math.random() * 500));
});
Solved
public static class mvcHelper
{
public static string variableReplace(string id)
{
string yazi = null;
if (id != null)
{
yazi = id.Replace('#', 'a').ToString();
}
else
{
yazi = id;
}
return yazi;
}
}
<div data-messageid="#mvcHelper.variableReplace(item.MessageId)" class="message-item">
<div class="hide message-content" id="message-content-#mvcHelper.variableReplace(item.MessageId)">

how to dynamically set text to an element in jquery

i have an onclick function that that calls a changeName function anytime a click event on that element happens.
function changeName() {
var frag = $('<span class="Name">change me</span>');
$( ".list" ).prepend(frag);
var x =[];
$('.ch-gname').each(function(index, obj)
{
x.push($(this).text());
for(i=0; i<x.length; i++) {
$('.Name').text(x[i]);}}});
$('#action').on('click', changeName);
HTML
<div>
<a href="#0" class="cb-pgcar"</a>
<span class="ch-gname">Greenhouse</span>
</div>
<div>
<a href="#0" class="cb-pgcar"</a>
<span class="ch-gname">tree house</span>
</div>
<div>
<a href="#0" class="cb-pgcar"</a>
<span class="ch-gname">light house</span>
</div>
<div class="list">
</div>
<div class="list">
</div>
<div class="list">
</div>
i want to able to change the text of the class Name to the text of class ch-gname. My function gives me only the last text text(lighthouse) for the three links.Any help please
The function changeName() has $('#action').on('click', changeName); but i do not see any element with id 'action'. Anyhow i've made necessary changes in order to make it work.
Added Action id to the elements
Changed the $('.Name').text(x[i]); to $('.Name')[i].innerHTML = x[i];
Look at the below example
function changeName() {
var frag = $('<span class="Name">change me</span>');
$(".list").prepend(frag);
var x = [];
$('.ch-gname').each(function(index, obj) {
x.push($(this).text());
});
for (i = 0; i < x.length; i++) {
$('.Name')[i].innerHTML = x[i];
}
}
$('#action').on('click', changeName);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a href="#0" class="cb-pgcar" </a>
<span id="action" class="ch-gname">Greenhouse</span>
</div>
<div>
<a href="#0" class="cb-pgcar" </a>
<span id="action" class="ch-gname">tree house</span>
</div>
<div>
<a href="#0" class="cb-pgcar" </a>
<span id="action" class="ch-gname">light house</span>
</div>
<div class="list">
</div>
<div class="list">
</div>
<div class="list">
</div>

How to hide an element based on another existing

I have a jQuery code that looks for a specific div element.
If the element exist I define a variable and use parseFloat() function. Since there are going to be more than one element with the same class I've created an array.
So far I've managed to hide the element called: div.ifc-balance-div; however I am not quite sure how I can hide the div.ribbon-yellow, in case the element does not have the variable savePrice.
(function($) {
"use strict";
$(document).ready(function() {
var j = 0,
savePrices = jQuery('.special-price .price .price').map(function() {
return parseFloat(jQuery(this).text().replace(/[^0-9\.]+/g, ""), 10);
}).get();
if(j < savePrices.length){
++j;
}
for (var i = 0; i < savePrices.length; ++i) {
if (Number(savePrices[i]) > 0) {
var ifcBalance = Number(savePrices[i]) / 1,
m = parseFloat(ifcBalance).toFixed(0);
$('div.ifc-balance-div' + (i + 1)).html('<p class="dynamic-badge-txt"><b>£' + m + ' OFF</b></p>');
$('div.ribbon-yellow').html('<div class="badge-ends-message">ENDS TUESDAY</div>');
}
else {
$('div.ifc-balance-div' + (i + 1)).hide();
}
}
});
})(jQuery);
Here is a sample of the HTML Code:
one having Save Price:
Text
<div class="price-box">
<p class="old-price">
<span class="price-label">Was</span>
<span class="price" id="old-price-15510">
<span class="price"><span class="currency">£</span>599</span> </span>
</p>
<p class="special-price">
<span class="price-label">You Save</span>
<span class="price" id="price-excluding-tax-15510">
<span class="price"><span class="currency">£</span>300</span> </span>
</p>
</div>
From
£299
One without save price:
<div class="ribbon-yellow"></div>
<div>
</div></div></div>
<a href="#" title="#">
<img src="#" alt="#">
</a>
</div>
<div class="item__detail">
<a href="#" title="#" class="item__link">
<p class="product-name item__name">Text</p>
</a>
<div class="price-range">
<span class="price-label">From </span>
<span class="price"><span class="price"><span class="currency">£</span>299</span></span>
</div>
</div>
</div>

Categories