jQuery each array using from single attr - javascript

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))
});

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)
});
}

How to iterate in Jquery over json string with multiple objects

I'm wondering how I can access each object in this json string via jquery.
The string returned looks like:
{"Appointments":["\/Date(1507238100000)\/"],"Sessions":[]}
I need access to both the Appointments object as well as the Sessions object, I can't seem to figure it out.
I tried to access the Appointments object by index like:
$.each(data, function (index, element) {
$.each(data, function (index, element) {
//alert(JSON.stringify(element, null, 4));
alert(element.Appointments[index]);
});
//value = new Date(parseInt(element.Appointments.substr(6)));
//var rowContent = "<tr><td>" + value + "</td></tr>";
//$('#appointmentsTable tbody').append(rowContent);
});
This does not work however, thoughts?
You don't have to access element by element.Appointments[index] when you are looping though an array by $.each.
For example
var data = {"Appointments":["\/Date(1507238100000)\/"],"Sessions":[]};
To loop though object in data.Appointments, you simply do this
$.each(data.Appointments, function(index, element){
console.log(element);
});
To loop though object in data.Sessions, you simply do this
$.each(data.Sessions, function(index, element){
console.log(element);
});
For more example about $.each, please refer to JQuery API Documentation here.
You don't actually need jquery for this at all.
You could use plain javascript. If your project uses ES6, you could write it as:
// extract appointments and sessions from data
let { Appointments, Sessions } = data
// iterate over appointments
Appointments.forEach((appointment, index) => { console.log(appointment) })
// iterate over sessions
Sessions.forEach((session, index) => { console.log(session) })
Basically you don't really need index inside your iteration callback - you can directly access the elements you are iterating over instead. The same would apply to your jquery function as well.
If you prefer to use jQuery, your code could be rewritten as:
$.each(data.Appointments, (index, elem) => alert(elem))

Reading values from label in Jquery

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
});

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

Populate a javascript array with links of a specific class

I'm looking to take a website source and populate an array with a collection of links, filtered by their a class.
Say, for instance, the links were <a class="title">, how could I target each class and add the URL to an array?
Would Javascript or jQuery work better?
var arr = new Array();
$("a.title").each(function()
{
arr.push($(this).attr("href"));
});
So, basically you create an array by using the Array constructor. Then you use JQuery's each method to iterate over the links with class title, getting their urls using the attr method and pushing them in the array along the way.
It's pretty easy with jQuery:
var arr = [];
var ptr = 0;
$('.title').each(function() {
arr[ptr] = $(this).attr('href');
ptr++;
})
Something like
var collectionOfLinks = {};
$('a').each(function() {
var cl = $(this).attr('class');
if (collectionOfLinks[cl] === undefined) {
collectionOfLinks[cl] = [];
collectionOfLinks[cl].push($(this).attr('href'));
}else{
collectionOfLinks[cl].push($(this).attr('href'));
}
});
With this you end up with an object whose properties names are the classes of the <a> elements and whose values are arrays of href
With jQuery, you can do var urls = $("a.title").attr("href")to get what you want.
You can do something like below,
var linkURL = [];
$('a.title').each (function () {
linkURL.push(this.href);
});

Categories

Resources