Create array from values of data fields in DOM elements [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In my page there are some article tags with an attribute data-course-id.
<article class="register" data-course-id="0123"></article>
<article class="register" data-course-id="0124"></article>
Now I would like to generate a variable which contains an array from the article tags and the value should be the same as the data-course-id.
var array = [0123, 0124]
How can I do this?

Like this:
var array = $('.register').map(function(){
return $(this).attr('data-course-id'); // converting to Number will result in loss
// of data since what you are using is octal representation.
}).get();

Without jQuery, you can try something like this:
var articles = document.getElementsByClassName("register");
var array = [];
for(var i = 0; i < articles.length; i++) {
array.push(articles[i].getAttribute("data-course-id"));
}
Working demo.

try like this,
$('.register').each(function(){
arr.push($(this).attr('data-course-id'));
alert($(this).attr('data-course-id'));
});
Live Demo Here..

Using jquery, I would do something like this
Pushing the data values:
var array=[]
$(".register").each(function(){
array.push($(this).data('course-id'));
});
alert("pushing only the data values:" + array)
Pushing the objects:
array2 = []
$(".register").each(function(){
array2.push($(this))
});
alert("pushing the objects: " + array2)
http://jsfiddle.net/x9LdR/1

Related

How to do array from the string ? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have an adress such as https://stackoverflow.com/#/schedulePage/some/another , how can I make it to an array with elements after # ?
var urlToSplit = "https://stackoverflow.com/#/schedulePage/some/another"
var onlyAfterHash = urlToSplit.split("/#/")[1];
var result = onlyAfterHash.split("/");
console.log(result);
Use the split function
var str = "https://stackoverflow.com/#/schedulePage/some/another";
var res = str.split("#");
I think you just want something like this.First here I just split out the string by #, grab the second part of split result i.e index 1 then again splitting the result with / and finally filter out the empty string from the generated array.
var string = 'https://stackoverflow.com/#/schedulePage/some/another';
var result = string.split('#')[1].split('/');
var filtered = result.filter((entry)=>entry.trim() != '');
console.log(filtered);

Javascript - Sum solution [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am getting below line in my source file and I would like to sum those values separated by pipe ("|")
There is no limit for the values coming in the line (might be 100 values)
10|20|30|40|[no limit for values] - Separator is pipe "|"
The ouptput would be 100
Please help to write a javascript function for the above query.
Regards
Jay
You should take a look at JavaScript's built-in functions: With split you can split your string into an array, with reduce you can 'reduce' your array to a single value, in that case via summation. These two links should provide you enough information for building your code.
You could try something like below:
function sum(value){
var total = 0;
var array = value.split(",").map(Number);
for( var i = 0; i < array.length; i++) {
total += array[i];
}
alert(total);
}
var value = "10|20|30|40".replace(/\|/g, ',');
console.log(sum(value));
https://jsfiddle.net/f7uqw7cL/

Convert word list into array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've tried to see if there were any scripts to convert a list of words into an array and I can't seem to find one.
Anyone know where I can find one?
Input:
Dog
Cat
Hamster
Gets converted to
["Dog", "Cat", "Hamster"]
Noo.. this isn't what I mean. I have a txt file with a bunch of words on each line and I was wondering if there was something out there already created that can convert each word into an array.
Just use split on the string.
For example:
var textarea = document.getElementById('list');
var arr = [];
textarea.addEventListener('input', function () {
arr = this.value.split('\n');
console.log(arr);
}, false);
Demo
If the string is actually "Dog\nCat\nHamster" then just do
"Dog\nCat\nHamster".split('\n');//returns ["Dog", "Cat", "Hamster"]
For a TextArea try this
myTextArea.value.split('\n'); // it will return desired output.
Where myTextArea is the TextArea you can get using getElement.
I think the best solution for a textarea input is using the match() function of javascript like this:
var words = []
$('textarea').on('blur', function(){
words = $(this).val().match(/\w+/g)
alert(words)
})
here a fiddle of it working.
This doesn't need for the words to be in different lines.

Parsing JSON in javascript for multiple JSON objects [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Should be quite a common answer but I haven't found it.
Using client-side javascript:
My client receives some JSON string:
response =
[
{"id1":"value1" , "time1":"valuetime1"},
{"id2":"value2" , "time2":"valuetime2"}
]
I understand that I can simply parse the JSON string with this command:
response = JSON.parse(response);
But what is the next command to access each of the objects individually?
I would prefer to not use jQuery.
In plain JavaScript, just use a simple for loop:
for(var i = 0; i < response.length; i++){
console.log(response[i]); // Object with id and time
}
-or-
response.forEach(function(object){
console.log(object);
});
Demo
This JSON will become the appropriate JavaScript object. In this case, that is an array which you can access the same way as you would any other JavaScript array:
for (var i = 0; i < response.length; i++){
console.log(response[i]);
}

How to apply substring to every letter in array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm making an array of textstrings like this:
phone = $(data).find('.tel a')
I would like to apply a substring(8) to every item in the array called phone. Is a for-loop the best way to do it?
phone, as it stands, contains a jQuery object, which is an Array-like Object of DOM elements. If you want to iterate over all of them and get their inner text, applying .substring(8) to each, and building an array out of them, you can use something like this:
var phoneArray = $(data).find(".tel a").map(function (i, el) {
return $(el).text().substring(8);
}).get();
DEMO: http://jsfiddle.net/96HWv/
(in the demo, I had to emulate what data could be, although I'm guessing it is an HTML string in your real code)
You can use the map() method :
phone = phone.get().map(function(e) { return $(e).text().substring(8) });
FIDDLE
You can use the .each() function for this... Something like:
$(data).find('.tel a').each(function() {
$(this).text(function(index,text) {
return text+"substring(8)";
});
});
You can let jQuery do the work for you.
$(data).find('.tel a').addClass('substring');
jQuery will traverse the array of elements returned and add the class to all of them.

Categories

Resources