Reading values from label in Jquery - javascript

I have many label and each of them has same class.My Label contains some information, which I need to read. How to read label attributes in Jquery. So far I could get object using $ but unable to get any value from its property.I need to get values for Id,Text, and title. Please help me to get those values .
$(".tagLabel").each(function (i, obj) {
var lableId = ?? // what I need to do with obj here to get it
var labelText=??
var lableTitle=??
});

Please try this:
$(".tagLabel").each(function (i, obj) {
var lableId = obj.id;
var labelText= $(obj).text();
var lableTitle= $(obj).attr('title');
});
Please note that you have to wait until your page is fully loaded, wrap your code with:
$(function() {
//Page fully loaded
//Put you code here
});

Related

How to retrieve a specific object from a JSON value stored in sessionStorage?

I have this stored in the session:
What I'm looking to do is assign each object in the JSON as a variable so I can add them to the DOM appropriately.
This works but prints everything out:
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
$(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9')).appendTo('.div');
}
What I'd like is something like this, but it doesn't work:
var div1 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.cart-contents')));
var div2 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.footer-cart-contents')));
var div3 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'div.widget_shopping_cart_content')));
Any help would be greatly appreciated. Thank you!
Getting the same value from the storage several times is not a good idea. In addition, you need better names for your variables.
var json = sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
if (json) {
var data = JSON.parse(json);
if (data) {
var cart_link = $(data['a.cart-contents']),
footer_link = $(data['a.footer-cart-contents']),
widget_div = $(data['div.widget_shopping_cart_content']);
}
}
So it appears you have set selectors as keys of the object so you could iterate those keys to get each selector.
The propose of those selector keys is not 100% clear. I am assuming that those selectors are the elements you want to insert the html strings into and that $() means you are using jQuery
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
var data = JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
$.each(data, function(selector, htmlString){
$(selector).append(htmlString)
});
}

What am I missing in the jQuery .each() function?

I have this function that I am trying to figure out/fix and can't seem to pinpoint the issue / can't figure out a way to get it working.
Basically my CMS is spitting certain hrefs that I would like to:
Part 1) change the targeted href URL
Part 2) change the button's text
Right now I only have 2 instances of this type of button, so here's what is printing out in my console:
Part 1) for this part I get the correct urls without the characters i want to strip out.
Part 2) two instances of the button's text (See All) followed by the correct variable of btnParent for the first button and then the second button and finally one instance of "Products".
My issue is, I can't figure out how to:
Part 1) send back the stripped URL to its respective button's href as an each function.
Part 2) Have the each() function print out the new text as "See All + BLAH + Products" for each instance, and then append the new text to the respective button.
Here is the code:
function viewMoreBtn() {
var btnMain = $("li:contains('See All')");
var btnText = $("li:contains('See All')").text();
var btnParent = $("li:contains('See All')").parent('ul').prev('li').text();
// PART 1 - STRIP LINK URL OF -_-// CHARACTERS
$.each(btnMain, function(i, v) {
v = $(this).find('a').attr('href').replace('-_-//', '');
console.log(v);
});
// PART 2 - ADD LABEL TO HTML TEXT OF BTN
$.each(btnMain, function(index, value) {
value = (btnText + btnParent + 'Products');
$(btnMain).text(value);
console.log(value);
});
}
viewMoreBtn();
Thank you.
jQuery objects, as return by $(...) have a each method already on them. The element is passed as the this context. You could use that further with jQuery to act on the objects in an scoped context. Basically, you have the right code, just in the wrong scope.
Part 1
btnMain.each(function() {
var $li = $(this);
var $a = $li.find('a');
var desiredUrl = $a.attr('href').replace('-_-//', '');
$a.attr('href', desiredUrl);
});
Part 2
btnMain.each(function() {
var $li = $(this);
var btnText = $li.text();
varbtnParent = $li.parent('ul').prev('li').text();
value = (btnText + btnParent + 'Products');
console.log(value);
$li.find('a').text(value);
});
See #Zequ's answer for the iteration over the each() function in the returned btnMain.
This is how $.each( obj, function( key, value ) works: you iterate over btnMain, and for each iteration of $.each(), the function assigns the index of the iteration to i and the value of btnMain at that index to v.
$.each(btnMain, function(i, v) {
//v = $(this).find('a').attr('href').replace('-_-//', '');
console.log(i); // I am the index of $.each() iterator
console.log(v); // I am the node from the btnMain array
// I don't know if this is right without seeing your HTML, but it seems like what you want
v.find('a').attr('href').replace('-_-//', '');
});
The second $.each() follows the same pattern.
If I understood correctly, you're confusing your variables.
$.each is a function for each element of the array/object being passed. It gives you a index and the element, check the reference
In part 1, you're defining v as the string you want, you're not changing the element at all,you need something like this:
$.each(btnMain, function() {
// you're saying you got the correct URLs, so the only thing you need to do is to change the element afterwards
var element = $(this).find('a');
v = element.attr('href').replace('-_-//', '');
element.attr('href', v);
});`
Also you could use btnMain.each instead of $.each
In part 2, you are changing the value variable (it's actually the element you're iterating over), to the string you want, then you follow it by trying to change btnMain's text. This is wrong, from what I understood, btnMain is an array of two elements you can't change it's text. You should change the element's value (that you are calling value). It would be something like that
$.each(btnMain, function(index, element){
// I think this is the time you want to define the btnParent, relative to the element
var btnParent = element.parent('ul').prev('li').text();
var value = (btnText + btnParent + 'Products');
element.text(value);
}
I THINK this is what you need.
Also you could append both parts into one, since both are iterating over btnMain

How to access multi level object data with jQuery

I have this code in js, on click this happens:
var self = $(this);
self.click(function(e){
e.preventDefault();
var nid = self.parents('.innerContainer').attr('nid');
var subjectTitleNID = settings.xxxxx.yyyy["nid-" + nid]
Via HTML I can find the NID value of InnerContainer, which is the main parent.
From the console, if I run Drupal.settings.xxxx.yyyyy (where xxxx and yyyy are my destinations), I get a list of objects which are children.
["nid-463"]
["nid-465"]
["nid-466"] etc ....
nid-466 is the value assigned to VAR NID.
But what I need to find now, is:
1. How many children there are in ["nid-466"]
2. What are their values
Usually I would run a simple for loop, but I don't know how to target those values.
For example, I would do this:
for (i=0; i < dont know what to put here .length; i++) {
> Drupal.settings.xxxx.yyyy[nid-466][nid-??] // this is incorrect
}
See image for more detailed structure.
Any ideas?
Thanks
George
Use $.each loor for this:
$.each(Drupal.settings.xxxx.yyyy[nid-466], function(index, value) {
// index is a key
// value is a object
// put your code here
// console.log(value.nid);
})

Modify a json array in hidden input?

I have a hidden input:
<input type="hidden" id="paidIds" name="paidIds" value="[]">
It starts with an empty array as its value.
I want to add and remove items from it but I cant work out how.
This is my code so far:
TO APPEND:
var $paidIds = $('#paidIds').val();
$paidIds.push($id);
$('#paidIds').val($paidIds);
TO REMOVE:
var $paidIds = $('#paidIds').val();
var $index = paidIds.indexOf($id);
if($index != -1) {
$('#paidIds').val().splice($index, 1);
}
$('#paidIds').val($paidIds);
So far one of the issues is $paidIds is still undefined after:
var $paidIds = $('#paidIds').val();
At a loss, and google is not helping -__-
EDIT
Got it working partly, in the debugger $paidIds = [4] but it did not set the value.
var $paidIds = JSON.parse($('#paidIds').val());
$paidIds.push($id);
$paidIds = JSON.stringify($paidIds)
$('#paidIds').val($paidIds);
EDIT2 fixed the missing #
You need to convert string to object.
Change:
$('paidIds').val()
to
$('#paidIds').val()
Try:
var $paidIds = $('#paidIds').val();
if($paidIds != ""){
$paidIds = JSON.parse($paidIds);
}
try to use JSON.parse when you read from the input, and use JSON.stringify when you set the input's value
I would suggest you store array an a data- attribute and use jQuery.data() to read it rather than parsing the value to an array.
HTML
<input id="paidIds" name="paidIds" data-array="[1,2,3]" value="[1,2,3]">
JS
/* Custom event to handle updates*/
$('#paidIds').on('updateArray', function (evt, newVal) {
var arr = $(this).data('array');
arr.push(newVal);
$(this).val(JSON.stringify(arr))
});
/* Useage*/
$('button').click(function () {
var newArrValue=$(this).data('val')
$('#paidIds').trigger('updateArray', [newArrValue]);
});
DEMO

jQuery each array using from single attr

I would like to know how can I make this work.
I have the following problem:
I have an element in HTML with rel="" attribute which includes product ids by which I display data from Json file.
Open data
And I would like to get this rel="" attr with jQuery and use it as array for each function.
My code right now is this:
var getProducts = jQuery('.openProducts').attr('rel');
$.each(getProducts, function(index, value) {
...
If I use this code it works:
var getProducts = [ '526231',' 487139', '528401', '521564' ];
$.each(getProducts, function(index, value) {
...
Thanks for any help.
use .split() - a regex is used because you don't want the space after ,
var getProducts = jQuery('.openProducts').attr('rel').split(/,\s*/);
var getProducts = jQuery('.openProducts').attr('rel').split(",");
$.each(getProducts, function(index, value) {
console.log($.trim(value))
});

Categories

Resources