JQuery get all data attributes from a list - javascript

I have a long dynamically generated list each with the same class identifier and a data attribute similar to the code below:
<ul>
<li class="list" data-id="123">One</li>
<li class="list" data-id="124">Two</li>
<li class="list" data-id="125">Three</li>
<li class="list" data-id="126">Four</li>
.....etc
</ul>
what I am trying to achieve is to get all the data-id values and format them in as follows:
123|124|125|126....etc
this would be then passed to a page via ajax and the id's checked for existence in a database.
var delimited_data="";
$('.list').each(function(){
delimited_data+=$(this).data('id')+"|";
});
console.log(delimited_data);
The reason I am asking this question is that I am working on a live system that automatically deploys items in the list columns to different users after 10 mins. I just need to be sure that the code is going the right way :)
I also need to check that is there are no .list classes on the page (ie - no way to do the query) whether delimited_data will be totally empty which I am pretty sure it would be.
Is there a better way than using .each() in this case as I find it can be rather slow baring in mind that the above function will be run every 30 seconds.

You can use .map to return an array:
var dataList = $(".list").map(function() {
return $(this).data("id");
}).get();
console.log(dataList.join("|"));
Demo: http://jsfiddle.net/RPpXu/

Use this:
var array = [];
$('li.list').each(function() {
array.push($(this).data('id'));
})
var joined = array.join('|');

Not an answer to your question but this is what i ended up on this page in search for and though it would help someone else :-)
var arrayOfObj = $('input').map(function() {
return {
name : $(this).attr('name'),
data : $(this).data('options'),
value : $(this).val(),
id : $(this).attr('id')
}
}).get();
console.log(arrayOfObj)
This returns an array of objects that mimics the input
Cheers!

as an update for #tymeJV answer for new versions of JavaScript you can use .map((index, elem) => return value) like this:
let result = $(".list").map((index, elem) => elem.dataset.id).get().join('|');

Related

How to get a specific class from a classlist array in a clean way?

I faced a problem today, i tooks me hours to just know what it is, so I had an element, this element had many classes :
<div id="myId" class="first second iwantthisone fourth"></div>
I was using a class from the list to pass it as a parameter in an other function, so to get it I was doing this :
const myClass = document.getElementById('myId').classList[2];
Why did I choose 2 ? because when I was doing a console.log to the classList, it was giving me an array ( not regular array ) and the result was like this :
['first', 'second', 'iwantthisone', 'fourth']
So I thought I have finished, I deployed my work to a server, I went there to test if everything is okay, it was not and that's why I am here, so the problem is that the order of the items in the array changed to this :
['second', 'iwantthisone','first', 'fourth']
So my old code in longer working, I need to do this :
const myClass = document.getElementById('myId').classList[1];
Which is not practical, I need to get the class using a method like filter for array, but it seems like I can't use it because classList is not a regular as I mentionned before.
Any solution ?
ANy help would be much appreciated.
You can use filter as long as you converted it from array using Array.from(). I'm skeptical that this is what youre looking for due to the discussion in the comments but from the question alone, this is the solution.
const myClassList = document.getElementById('myId').classList;
var classList = Array.from(myClassList).filter(word => word == "iwantthisone");
console.log(classList);
console.log(myClassList);
<div id="myId" class="first second iwantthisone fourth"></div>

Show only the latest 3 results using a loop in JavaScript

I have a script that pulls in results and displays it on my site. I want to display only the last three results that are being pulled instead of everything. So the latest results are Test2, Test1 and then Office 365 Planned Service.
Here are all the results being pulled:
Here is my JavaScript code:
$(document).ready(function(){
$pnp.setup({
baseUrl: "https://fh126cloud.sharepoint.com/TrainingResourceCenter/O365Training"
});
$pnp.sp.web.lists.getByTitle("O365RoadMap").items.orderBy("Created", false).get().then(function(items) {
console.log(items);
var result = items.map(item => {
return {
Title: item.Title,
Description: item.Description,
Link: item.Link
}
});
var $table = roadMapDisplay(result);
console.log($table);
$('#title').html($table);
});
function roadMapDisplay(items) {
var table = $('<container/>');
items.forEach(item => {
table.append(`${item.Title}`);
table.append(`<div style="text-indent: 10px">${item.Description.slice(0, -200)}...</div>`);
table.append('<br/>');
});
return table;
}
});
How could I throw a loop onto that function? I've tried so many different ways and have come short.
Thanks all in advance!
The following is specific to arrays. However, it appears there's a $pnp-specific answer which it seems to me should be more efficient.
Assuming your current code works (showing the full list), you can grab just the first three entries in items like this:
items = items.slice(0, 3);
...or the last three like this:
items = items.slice(-3);
I am guessing that $pnp is the PnP JavaScript Library With jQuery In SharePoint based on a quick search online.
I don't know too much about PnP; however, I noticed this documentation in https://github.com/SharePoint/PnP-JS-Core/wiki/Working-With:-Items:
// use odata operators for more efficient queries
$pnp.sp.web.lists.getByTitle("My List").items.select("Title", "Description").top(5).orderBy("Modified", true).get().then((items: any[]) => {
console.log(items);
});
As you can see they are using "top(5)"; therefore, you could change the order, so you get first the last elements, then use top(3) to obtain those three records you wish to display.
Since $pnp seems to follow a chain pattern, I wonder if you could apply again the order method after obtaining the top(3).
To keep two arrays:
var items = [1,2,3,4,5,6]
var n = 3
var remainingArray = items.splice(0, items.length-n);
console.log(remainingArray)//<--first n elements
console.log(items)//<--last n elements
I think your are looking for this. if our query always returns top three items then why we explicitly goes to javascript?
$pnp.sp.web.lists.getByTitle("O365RoadMap").items.top(3).orderBy("Created", false).get().then(function(items) {
console.log(items);
});
you can get more knowledge from here

isbn de-duplicate with javascript/jquery

Brief background: I retrieve book info from google books and worldcat via each api. I parse through the data to create an html div outputs with stuff of interest for a webapp.
The problem: the isbns. After getting isbns from each, I merge them into one div. For example:
<span id='tada'>9781137012920 9780230339118 9781137012920 1137012927</span>
I would like to eliminate the duplicate isbn (e.g., 9781137012920) with either javascript or jquery. I can get the text of the span but every solution I have tried has failed thus far.
Any help - esp, with a codepen or fiddle - for this amateur would be greatly appreciated.
PS:I know variations of this question have been addressed on StackOverflow - and believe me that I am sick of duplicates! - but I have not managed to fix this after a couple of days of trying. Examples that type in the content as var work but how do I get it from the div and make it work?
Do something like this using text() method with callback
$('span').text(function(i, v) { // use callback to get old value
return v.split(' ') // split the old value
.filter(function(v1, i, arr) { // v1 is array element, i is index, arr is iterating array
return arr.indexOf(v1) == i; // filter unique value by checking the index
}).join(' ') // join and return the unique values
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='tada'>9781137012920 9780230339118 9781137012920 1137012927</span>
For more about finding unique array element refer : Remove Duplicates from JavaScript Array
I suggest removing the duplicates before making them into the div. If you are getting the values in an array you can eliminate the duplicates easily. Remove Duplicates from JavaScript Array
I think you want something like this :
var string = $('span').text();
var uniqueList=string.split(' ').filter(function(allItems,i,a){
return i==a.indexOf(allItems);
}).join(' ');
$('#output').append(uniqueList);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div>
<h1>Input</h1>
<span>9781137012920 9780230339118 9781137012920 1137012927</span>
</div>
<div id="output">
<h1>Becomes</h1>
</div>

Values of all textboxes on a page - without knowing the ID?

I am developing a Chrome Extension that, when the user leaves the page, saves all the text from the textboxes on that page and outputs it to a file.
If I knew the IDs of the textboxes on the page, then it wouldn't be a problem, but the issue is that I need the extension to get the values of all of the textboxes on the page without knowing the IDs, as it will be a different website each time the extension is used.
Also, how would the information be collected? In a string? It would be nice to go down the page and add each textbox to a file, one by one, instead of one huge string.
I've never used jQuery or understood it, and there's probably a solution in it staring me in the face. If anyone suggests using it, please could you explain it a little bit?
Thanks in advance. I would post my code, but I don't know where to start - ergo I don't have any.
you could store it in array using $.each, as :
var valsArr = [];
$("input[type=text]").each(function() {
valsArr.push( $(this).val() );
});
or create object with name as key and value as its value, like:
var valsObj = {};
$("input[type=text]").each(function() {
valsObj[this.name] = $(this).val();
});
You can do it like this:
function onClick(){
var areas = document.getElementsByTagName("textarea");
for(var i = 0; i < areas.length; i++){
alert(areas[i].value);
}
}
<textarea></textarea>
<textarea></textarea>
<button onclick="onClick()">Gather information</button>
Also see this regarding your "save to a file" question Using HTML5/Javascript to generate and save a file
Use the selector and apply it in an each cycle.
$(":text").each(function(){
alert($(this).val());
});
Make a for loop
for(i=0; i < $("input[type='text']").length; i++){
$("input[type='text']").index(i).value();
}
You can use .map() : It returns an array.
var arr = $(":text").map(function() {
return this.value
}).get(); //add join(',') after get() to get a simple comma separated list.
Instead of input[type="text"] you could also use :text pseudo selector.
Demo

this.value only returning first two characters

I'm attempting to find the value of all elements with the class bm-user-label, and put it into a javascript array. However when I do this I only get the first two characters of the value field. For instance for:
value="30bb3825e8f631cc6075c0f87bb4978c"
I get returned
30
The DOM looks like
<li value="30bb3825e8f631cc6075c0f87bb4978c" class="cboxElement bm-user-label">first</li>
And my javascript is:
var com_labels = $('.bm-user-label').map(function() {
return(this.value);
}).get();
Any ideas?
<li> elements are not defined to have a value. You should get this attribute using this.getAttribute("value") instead.
In an effort to follow the doctype standards, you should use data attributes for non-native attributes:
<li data-value="30bb3825e8f631cc6075c0f87bb4978c" class="cboxElement bm-user-label">first</li>
And query it as such:
var com_labels = $('.bm-user-label').map(function() {
return($(this).data('value'));
}).get();
http://jsfiddle.net/sTdWY/

Categories