How to add div id name to array - javascript

At the page I have these divs:
<div id="question-688">
</div>
<div id="test">
</div>
<div id="stats-654">
</div>
<div id="answer-636">
</div>
<div id="someDiv">
</div>
I would like to create an array with these numbers: 688, 654, 636. So when id of div is started with question or answer or stats, I want to add number belongs to this ID to array. How can I do this via javascript?

You can use a plain css selector with method document.querySelectorAll.
I used Array.prototype.map.call because the previous method returns a NodeList not an Array, then you can use map and pass it a function to extract the ids of your divs.
Demo here
var selector = 'div[id^=stats-],div[id^=answer-],div[id^=question]',
ids = Array.prototype.map.call(document.querySelectorAll(selector), function (div) {
return div.id.split('-')[1]|0; // this returns the id as an integer
});

Here is a working jsBin : http://jsbin.com/pecaj/1/edit
var arrayOfNumbers = [];
var divArray = document.querySelectorAll("div");
for(var index = 0; index<divArray.length; index++) {
var id = divArray[index].id;
if(id.match(/\d+$/)) {
arrayOfNumbers.push(parseInt(id.match(/\d+$/),10))
}
}
console.log(arrayOfNumbers)
It fetches the number for div ids and adds them to an array.
Hope its useful to you :)

Only ONE instruction if you use jquery :
var yourArray=$('div[id^=stats],div[id^=question],div[id^=answer]').toArray().map(function(e){return $(e).attr('id').split('-')[1]}) ;
See fiddle : http://jsfiddle.net/abdennour/LBc5u/

Very simple:
var divs = document.getElementsByTagName('div');
var divIDs = [];
var r = /\d+/;
for (var i =0; i < divs.length; i++) {
if (divs[i].id.length > 0 && ( divs[i].id.indexOf("question") !=-1 || divs[i].id.indexOf("answer") !=-1 || divs[i].id.indexOf("stats") !=-1 ))
divIDs.push((divs[i].id).match(r));
}
Demo http://jsfiddle.net/P3LPn/

maybe something like this? Create a map and them use the map to refer to your DIV's
var map = {};
// add a item
map[key1] = value1;
// or remove it
delete map[key1];
// or determine whether a key exists
key1 in map;

Related

Passing array elements to foreach divs

I'm trying to pass string elements from an array myArr while selecting the div it should go into with a forEach loop, so that each of the four div elements below has a corresponding string element from the array.
I'm having some trouble with it, because I'm selecting the divs with a querySelectorAll method. Help would be appreciated. This code below is just a sample of what I'm working on, so it can't be altered too much.
HTML
<div class="number">old number</div>
<div class="number">old number</div>
<div class="number">old number</div>
<div class="number">old number</div>
JS
var numberDivs = document.querySelectorAll(".number");
var myArr = ['number1','number2', 'number3', 'number4'];
numberDivs.forEach(function(el) {
el.innerHTML = "new number";
for (var i = 0; i < myArr.length; ++i) {
el.innerHTML = myArr[i];
}
});
Right now, it's (el) only passing through the last element in the array to all divs, instead of the corresponding one.
I think is this what you want:
numberDivs.forEach(function(el, i) {
el.innerHTML = myArr[i];
});
This assumes they are of equal length, and won't overwrite each element's HTML like your code is currently doing.
var numberDivs = document.querySelectorAll(".number");
var myArr = ['number1','number2', 'number3', 'number4'];
for (var i = 0; i < myArr.length; i++) {
numberDivs[i].innerHTML = myArr[i];
}
You're issue was you had a for loop going across all the elements, then another for loop going across your array. The inner for loop, the one for you're array, would always end at the last element, therefore each object - the divs - ended at the final element of that array.
http://jsfiddle.net/a8zrkejo/
Quick fix, if you're certain the total count of the array is same as the number of divs
then loop the array only and use the index of each element to access the div.
var numberDivs = document.querySelectorAll(".number");
var myArr = ['number1','number2', 'number3', 'number4'];
myArr.forEach(function(value, Index) {
numberDivs[Index].innerHTML = value
});

Angular js function to add counts based on match in names

I have an angular app in this plunker
I have a text area which has some text in the format of (key,count) in them by default.
What i am trying to achieve is this(in the calc() function):
When the button is pressed the results of the summation should be displayed.
I was able to split the data from the textarea into different arrays but i am missing the logic to add when the names match.
EDIT:
please notice a few updates in my plunker
New to angular and javascript!
This should do it.
JS:-
$scope.calc = function() {
$scope.users = {};
$scope.values.split('\n').forEach(function(itm){
var person = itm.split(','),
name,
key;
if(! itm.trim() || !person.length) return;
name = person[0].trim()
key = name.toLowerCase();
$scope.users[key] = $scope.users[key] || {name:name, count:0};
$scope.users[key].count += +person[1] || 0;
});
}
HTML:-
<div class="alert alert-success" role="alert">
<ul>
<li ng-repeat="(k,user) in users">The total for {{user.name}} is {{user.count}}</li>
</ul>
</div>
Demo
Add shim for trim() for older browsers.
Here's another way to do it. I can't speak to performance against PSL's method, but I think this reads a little easier to my not-very good at javascript eyes.
function groupByName(names) {
inputArray = names.split('\n');
outputArray = {};
for (i = 0; i < inputArray.length; i++) {
var keyValuePair = inputArray[i].split(',');
var key = keyValuePair[0];
var count = Number(keyValuePair[1]);
// create element if it doesnt' exist
if (!outputArray[key]) outputArray[key] = 0;
// increment by value
outputArray[key] += count;
}
return outputArray;
}
This will produce an object that looks like this:
{
"John": 6,
"Jane": 8
}
You can display the name of each property and it's value with ng-repeat:
<li ng-repeat="(key, value) in groupedNames">
The total for {{key}} is {{value}}
</li>
It's not an overwhelmingly complex bit of javascript, depending on the number of name value pairs. So you can probably even get rid of the manual calc button and just put a $watch on values in order to automatically recalculate totals with every change.
$scope.$watch('values', function() {
$scope.groupedNames = groupByName($scope.values);
});
Demo in Plunker
You can build a TotalArray with the actual name (key) of your input as key and the count as value with it. Iterate over the input pairs and check if there is already a key called the key of this iteration if so: add the count to its value, otherwise create a new one in the TotalArray.
Some pseudo code that might help you:
inputArray = text.split('\n')
outputArray = []
for(i = 0, i< length, i++) {
name = inputArray[i].split(',')[0]
count = inputArray[i].split(',')[1]
if (outputArray[name] exists) {
outputArray[name] += count
} else {
outputArray[name] = count
}
}
Now outputArray contains [[name1] => total_count1, [name2] => total_count2,... ]
I hope this helps you.

Obtain a substring of a string using jQuery

I have a div with the following classes:
form-group val-presence-text val-type-pos-int val-length-10 has-success has-feedback
I want to get the 10 from the val-length-10 class name. I've tried various methods, but none seem to work for a dynamic multi-class attribute such as this. In addition, the 10 could be any positive integer and the class could be located anywhere within the group of classes.
Any ideas?
You can use this:
var val_length = $('div').attr("class").match(/val-length-(\d+)/)[1];
One possible solution:
var n = (this.className.match(/val-length-(\d+)/) || []).pop();
Or in the context:
$('[class*="val-length-"]').each(function() {
var n = (this.className.match(/val-length-(\d+)/) || []).pop();
console.log(n);
});
Assuming that the it is 'val-length' that never changes and just the integer on the end of it, you should be able to do this:
//get an array of classes on a specific element
var classList =$('#elementId').attr('class').split(/\s+/);
//loop through them all
$.each( classList, function(index, item){
//check if any of those classes begin with val-length-
if (item.indexOf('val-length' === 0) {
console.log(item.substring(11))
}
});
Try this...
$("div[class*=val-length-]").each(function() {
var s = this.className;
var length = 0;
$(s.split(" ")).each(function() {
if (this.search("val-length-") === 0) {
length = this.substr(11);
}
});
console.log(length);
});
It will find the relevant div and pull the value for you.

Javascript/jquery create array from elements with same rel?

How can you create an array with from a set of elements with same rel?
Eg:
<a rel='array' id='2' url='aa'></a>
<a rel='array' id='5' url='bb'></a>
<a rel='array' id='8' url='cc'></a>
Array:
[2] > aa
[5] > bb
[8] > cc
I put each URL as value just to use something. But having the IDs ordered should be enough.
How can this be done?
const anchors = document.getElementsByTagName('a'), arr = [];
for (let i = 0; i < anchors.length; i++){
let current = anchors[i];
if(current.getAttribute('rel') == 'array') {
// arr.push(current.getAttribute('url'));
arr.push({ 'id' : current.id, 'url' : current.getAttribute('url') });
}
}
http://jsfiddle.net/8ScSH/
Or, more succinctly:
const anchors = [...document.getElementsByTagName('a')];
const arrs = anchors.filter(x => x.getAttribute('rel') === 'array')
.map(x => { return { 'id': x.id, 'url': x.getAttribute('url') } });
Not enough jquery!
var arr = [];
$('a[rel="array"]').each(function(){
arr.push($(this).attr('url'));
});
Very easy if you're using jquery:
var arr = [];
$('a[rel="array"]').each(function() {
arr.push($(this).attr('url'));
});
​
Fiddle
var itemArray = [];
$("a[rel='array']").each(function() { itemArray.push($(this).attr("url") });
Try
var a = {};
$('#wrap a').each(function() {
if($(this).attr('rel') === "array") {
a[$(this).attr('id')] = $(this).attr('url');
}
});​​
An array won't cut it, you need an object. Here live: http://jsfiddle.net/martincanaval/rAPkL/
var elements = [];
$('a[rel="array"]').each(function() {
elements[this.id] = $(this).attr('url');
});
Note that this creates a sparse array with only the index values specified by the element ids, which doesn't make much sense to me, but that's what you asked for. It really doesn't make sense if any of the ids can be non-numeric - if so you should use an object rather than an array, i.e.:
var elements = {};
"I put each URL as value just to use something. But having the IDs ordered should be enough."
If your intention is to get an array of the ids then you can do this:
var elementIds = [];
$('a[rel="array"]').each(function() {
elementIds.push(this.id);
});
That would create the array ['2', '5', '8'] where the ids will be in the order that they appear within your source html.
However, just saying $('a[rel="array"]') gives you a jQuery object that is an array-like structure holding all the matching elements - that's why we can iterate over each of the elements using the .each() method. So it's possible that whatever you're really trying to do can be done directly with jQuery rather than setting up your own array.

Splitting classes & matching them against another DIV. JQuery

I have a div named box which contains three classes. I want to create a variable named relatedBoxes that stores the check boxes that share any of the same classes that box has.
I am splitting up the classes and storing them in the variable named splitClass.
I now just need the method to see whether :checkbox contains any of the classes saved within splitClass. I have tried by creating the variable relatedBoxes but this doesn't quite work.
The markup:
<div id="box" class="marker blue large">
The JavaScript:
var c = $('#box').attr('class');
var splitClass = c.split(' ');
var relatedBoxes = $(':checkbox').hasClass(splitClass);
Thanks a lot guys
hasClass expect a single class name, you're passing it an array right now. If you're trying to find all elements with marker, blue or large, something like:
var relatedBoxes = $( ':checkbox' ).filter( '.' + splitClass.join( ',.' ) );
You can use .filter() [docs] and iterate over the classes of the element:
var splitClass = $('#box').attr('class').split(' ');
var relatedBoxes = $('input[type="checkbox"]').filter(function() {
for(var i = 0, len = splitClass.length; i < len; i++) {
if($(this).hasClass(splitClass[i])) return true;
}
return false;
});

Categories