I am misunderstanding a jQuery array - javascript

This code doesn't work
var next = $("#orders").find(".next");
if (next.length == 1) {
var address = $(next[0]).find(".directionsAddress");
var destination = $(address[0]).text();
}
It is suppose to find one div with a class of "next" that I know exists on the page, then within that one item of the result set array, there will be one div with a class name of directionsAddress. The "next" array is coming back with a length of 1, so it looks like the problem is with my $(next[0]).find because the address array is coming back as 0 length and I am making a syntax error of some sort that I don't understand.

are you looking to do something like this?
$(document).ready(function() {
alert($('#orders div.next:first div.directionsAddress:first').text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "orders">
<div class="next">
<div class="directionsAddress">THIS IS WHAT I WANT</div>
<div class="directionsAddress">This is not the one I want</div>
</div>
<div class="next">
<div class="directionsAddress">This is not the one I want</div>
</div>
<div class="next">
<div class="directionsAddress">This is not the one I want</div>
</div>
</div>

Related

How to get the first class from two same classes with cheerio

currently i'm making a web scraper with node.Js using cheerio. i want to get the data inside the first of class="panel-items-list.
the html look like this
<div class="margin-bottom-=30">
<div class="side-list-panel">
<ul class="panel-item-list">...</ul>
</div>
</div>
<div class="margin-bottom-=30">
<div class="side-list-panel">
<ul class="panel-item-list">...</ul>
</div>
</div>
i already did like this
const relateArticle = $('.panel-items-list').map((i, section)=>{
let articles = $(section).find('h5');
return articles.text();
}).get();
but it return the data from both class="panel-items-list". how do i get data just from one class ? sorry my english is bad. thanks in advance !
To get the first class only from the .panel-item-list use .get(0) that means you are only selecting the first index found using .map
Also, in your current code jQuery your are not selecting the right class selector.
In addition use .trim() method when getting the text to clean up any unseen spaces within the text.
Live Working Demo:
const relateArticle = $('.panel-item-list').map((i, section) => {
let articles = $(section).find('h5');
return articles.text().trim();
}).get(0)
console.log(relateArticle) //Foo
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="margin-bottom-=30">
<div class="side-list-panel">
<ul class="panel-item-list">
<h5>
Foo
</h5>
</ul>
</div>
</div>
<div class="margin-bottom-=30">
<div class="side-list-panel">
<ul class="panel-item-list">
<h5>
Bar
</h5>
</ul>
</div>
</div>
Use first():
$('.panel-items-list').first().find('h5').text()

Copy first character of string to another div jquery or javascript

Is it possible with jQuery or Javascript to copy the first character of a string that's user generated to another div?
As an example, the contact list on iPhone. The first letter of the contact name is used in the circle adjacent to the name.
With the correct snippet the output would be as follows, where 'First name, Last name' will be different.
<div class="initial">F</div>
<div class="name">First name, Last name</div>
<div class="initial">J</div>
<div class="name">John Smith</div>
I tried to get some ideas from these other posts:
How do I make the first letter of a string uppercase in JavaScript?
How can I get the first three letters of a string in JQuery?
Detect character in div and remove it Javascript or jQuery
However, I'm not sure where to start and how to output the result to the 'initial' div.
The simple way to do this is to provide a function to text() of the .initial elements which reads the first character from the sibling .name and returns it, like this:
$('.initial').text(function() {
return $(this).next('.name').text().slice(0, 1).toUpperCase();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="initial"></div>
<div class="name">Foo Bar</div>
<div class="initial"></div>
<div class="name">John Smith</div>
a vanilla JS solution i came up with:
https://jsfiddle.net/y0c9be6g/
<div class="initial"></div>
<div class="name">Bob Smith</div>
<div class="initial"></div>
<div class="name">Jim Halpert </div>
<div class="initial"></div>
<div class="name">Billy Baldwin</div>
<script>
var names = document.querySelectorAll(".name");
var initials = document.querySelectorAll(".initial");
function addInitial(item){
item.previousSibling.previousSibling.innerHTML = item.textContent.charAt(0);
}
names.forEach(addInitial);
</script>

jQuery select another element with certain class in same parent

let say i have this div
<div id='parent'>
<button id='button'></button>
<div id='child'>
<div id='grandchild' class='lookAtMe'>
Some JSON text
</div>
</div>
</div>
I wanted to give the #button an on click event that returned the text at #lookAtMe div, specific to the div whom it shares parent/grandparent (in this case, the #parent div)
I tried using:
$("#button").on("click",function(){
var ReturnedText = $(this).parent(".lookAtMe").text();
console.log(RetrunedText);
});
But the console log would retruned (empty string).
Where did i do wrong? please help. Thankyou very much.
Because there is n o parent with that class. You need find().
Actually you need to write
var ReturnedText = $(this).parent().find(".lookAtMe").text();
$("#button").on("click",function(){
var ReturnedText = $(this).parent().find(".lookAtMe").text();
console.log(ReturnedText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent'>
<button id='button'></button>
<div id='child'>
<div id='grandchild' class='lookAtMe'>
Some JSON text
</div>
</div>
</div>

Scope issue in Javascript when writing to an array

BACKGROUND
I have a list of buyerNames and want the admin user to be able toggle their names. So far so good. Visually it works as expected. Admin user clicks on name and it's toggled on (background around the name and the items changes shade). Admin user can click and unclick names to his heart's desire.
CODE BELOW: I'm showing large sections of my code in case I'm messing something up in
a place where I don't think there's a problem.
<div class="headerSecondaryBg"> <!-- THE BACKGROUND LAYER - POSITION AND COLOR -->
<div class="buyerItems"> <!-- NUMBER OF BUYER ITEMS -->
<div class="item i1">42</div>
<div class="item i2">31</div>
<div class="item i3">57</div>
<div class="item i4">49</div>
<div class="item i5">16</div>
<div class="item i6">38</div>
<div class="item i7">24</div>
</div>
<div class="buyerNames"> <!-- BUYER NAMES -->
<div class="buyer b1">BUYERNAME 1 </div>
<div class="buyer b2">BUYERNAME 2 </div>
<div class="buyer b3">BUYERNAME 3 </div>
<div class="buyer b4">BUYERNAME 4 </div>
<div class="buyer b5">BUYERNAME 5 </div>
<div class="buyer b6">BUYERNAME 6 </div>
<div class="buyer b7">BUYERNAME 7 </div>
</div>
<div class="selectBuyer"> <!-- CREATES THE VISIBLE ON / OFF FOR THE TOGGLE AS PER DESIGN SPEC -->
<div class="selectBuyerOff b-on1"></div>
<div class="selectBuyerOff b-on2"></div>
<div class="selectBuyerOff b-on3"></div>
<div class="selectBuyerOff b-on4"></div>
<div class="selectBuyerOff b-on5"></div>
<div class="selectBuyerOff b-on6"></div>
<div class="selectBuyerOff b-on7"></div>
</div>
</div><!-- // END headerSecondaryBg -->
BACKGROUND
After the admin user has selected his buyers he clicks "show items" to reveal a hidden div below.
PROBLEM: Putting the toggled names into an array.
STEP 1:
Get buyerName (b-on1, b-on2 ... in this test example) and place in array.
$(".selectBuyer div" ).click(function(){
$(this).toggleClass("selectBuyerOn"); // show user that items are on or off
var all=$(this).attr('class');
console.log(all);
console.log = selectBuyerOff b-on1 selectBuyerOn.
EXACTLY WHAT WAS EXPECTED (considering I clicked on buyer 1)
STEP 2:
OK. Let's just have b-on1 and get rid of the other classes.
$(".selectBuyer div" ).click(function(){
$(this).toggleClass("selectBuyerOn"); // show user that items are on or off
var all=$(this).attr('class');
bbb=$(this).attr('class').split(' ')[1];
console.log(all);
console.log(bbb);
I get what's expected:
console.log(all) = selectBuyerOff b-on1 selectBuyerOn
console.log(bbb) = b-on1
STEP 3:
NOW let's put it into an array. (This goes immediately after the above code)
testArr=[];
testArr.push(all);
testArr.push(bbb);
console.log(testArr);
console.log = ["selectBuyerOff b-on1 selectBuyerOn", "b-on1"]
Now here's the problem - the array resets itself after every click.
I want the array to have b-on1 and b-on2 if the user selected those and
b-on1 and b-on2 if the user selected b-on1, b-on2, b-on3 (and then untoggled b-on3)
and yet the array is reset after every click.
How do I get this to work?
I tried removing var so that the variable would be in the global scope. I must be missing something simple.
When testArr=[] is executed, the testArr variable is assigned to a brand new empty array.
It sounds like you need to initialize this array just the once outside of the click handler, and then simply push values into the existing array within the handler. For example:
var testArr = [];
$(".selectBuyer div" ).click(function(){
$(this).toggleClass("selectBuyerOn"); // show user that items are on or off
var all=$(this).attr('class');
bbb=$(this).attr('class').split(' ')[1];
testArr.push(all);
testArr.push(bbb);
console.log(testArr);
/* ... */
});

Get specific data from page and write it to div

I'm building an online store with javascript shopping cart. However, the script doesn't allow printing only one or two values when displaying cart, but I need to do this.
Here's what the cart looks like:
<div class="simpleCart_items">
<div>
<div class="headerRow">
<div class="item-name">Tuote</div>
<div class="item-price">Hinta</div>
<div class="item-decrement">-</div>
<div class="item-quantity">Määrä</div>
<div class="item-increment">+</div>
<div class="item-total">Yhteensä</div>
<div class="item-remove">Poista</div>
</div>
<div class="itemRow row-0 odd" id="cartItem_SCI-1">
<div class="item-name">Teipit</div>
<div class="item-price">€0.00</div>
<div class="item-decrement"><img src="css/minus.png" alt="minus">
</div>
<div class="item-quantity">3</div>
<div class="item-increment"><img src="css/plus.png" alt="plus">
</div>
<div class="item-total">€0.00</div>
<div class="item-remove"><img src="css/remove.png" alt="Remove">
</div>
</div>
<div class="itemRow row-1 even" id="cartItem_SCI-3">
<div class="item-name">Car Speaker -hajuste</div>
<div class="item-price">€4.00</div>
<div class="item-decrement"><img src="css/minus.png" alt="minus">
</div>
<div class="item-quantity">1</div>
<div class="item-increment"><img src="css/plus.png" alt="plus">
</div>
<div class="item-total">€4.00</div>
<div class="item-remove"><img src="css/remove.png" alt="Remove">
</div>
</div>
<div class="itemRow row-2 odd" id="cartItem_SCI-5">
<div class="item-name">Teipit (Musta hiilikuitu)</div>
<div class="item-price">€0.00</div>
<div class="item-decrement"><img src="css/minus.png" alt="minus">
</div>
<div class="item-quantity">1</div>
<div class="item-increment"><img src="css/plus.png" alt="plus">
</div>
<div class="item-total">€0.00</div>
<div class="item-remove"><img src="css/remove.png" alt="Remove">
</div>
</div>
</div>
</div>
NOTE: The cart is written via javascript so it isn't visible in page source, only in inspect mode of the browser.
So how would I gather the item-name, item-priceand item-quantity?
I've tried this:
var name = $('.item-name');
var price = $('.item-price');
var quantity = $('.item-quantity');
var data = name + price + quantity;
$('#items').html(data);
But this won't actually do anything.
When doing this -> $('.item-name');
You are just capturing the element as object but not the value.
Now that you got your element as object, you need to extract the value and, in this case, your element object is a div so you can try .text() or .html() (to get the text or html inside the div).
(For this situation I will use text() cause you are working just with values and there is nothing related to html)
Try this:
var name = $('.item-name');
var price = $('.item-price');
var quantity = $('.item-quantity');
var data = name.text() + price.text() + quantity.text();
$('#items').html(data);
Better solution:
This will make clickable the div in which you have the product and match the cartItem_SCI pattern.
So, when user clicks any of the elements of your cart, you will get the name, price and quantity values that will be attached to the $('#items') div using append() method instead of html() (because using this will replace the product information each time the user clicks a div)
$(document).ready(function() {
$('div[id^="cartItem_SCI-"]').css({ cursor:'pointer' });
$('div[id^="cartItem_SCI-"]').click(function() {
var name = $(this).find('.item-name');
var price = $(this).find('.item-price');
var quantity = $(this).find('.item-quantity');
var data = name.text() + ' - ' + price.text() + ' - ' + quantity.text();
$('#items').append(data + '<br/>');
});
});​
You are just getting a reference to the class, add .html() to get the inner html of the element that the class applied to.
var name = $('.item-name').html();
For one item you can get like this.But since you have multiple items make one object like this .
var item={};
$('.item-name').each(function(){item.name=$(this).html()});
$('.item-price').each(function(){item.price=$(this).html()});
$('.item-quantity').each(function(){item.quantity=$(this).html()});
var data='';
for(var i=0;i<item.length;i++)
{
data+=item[i].name+item[i].price+item[i].quantity;
}
$('#items').html(data);

Categories