I have an array inside an $.each function. I want to iterate through it to create a new or modified array. But I need to access the $(this) from the outside $.each loop:
// target these data attributes:
$selector = $('[data-my0], [data-my1], [data-my2]');
$.each($selector, function() {
var $this = $(this), // cache selector
keys = ['my0', 'my1', 'my2']; // array of data keys
// I want to use the keys array to make a vals array to this:
// var vals = [$this.data('my0'), $this.data('my1'), $this.data('my2')];
// This doesn't seem to work (can't read from length 0 error):
var vals = $.map( keys, function( key ) { return $this.data(key); });
});
I think it's possible to do this using using $.each or $.map but this is where I'm stuck. I know $(this) not used normally with $.map like it is with $.each. In this case, I'm trying to pass the $this from the outside that represents the selector.
Wait - you're passing "vals" into your "$.map()" cal instead of "keys":
var vals = $.map( keys, function( key ) { return $this.data(key); });
Here is a jsfiddle. The code works just fine, though without seeing your actual HTML it's hard to know exactly what you expect to happen.
Related
I want to create objects in a foreach loop:
I'm starting from this:
data.forEach(function (el) {
var dynamic_var = new Quill(el['editor']);
dynamic_var.on('text-change', logHtmlContent);})
But, dynamic_var is 'overwritten', and I want to remain unique.
I check some html elements, and for each one that I found I want to create a new Object, and execute the Object methods.
In my case the variable get a new object per each iteration, is not a new variable.
Is this what you were looking for?
var quillValueContainer = {};
// ...
data.forEach(function(el) {
quillValueContainer[el] = new Quill(el['editor']);
quillValueContainer[el].on('text-change', logHtmlContent);
});
This will only work if el is a string, or number. Seeing how you are using it like this: el['editor'], makes me thing it's an Object, in which case, you can instead use the indices of the elements.
var quillValueContainer = {}; // [] should also work for indexes
// ...
data.forEach(function(el, index) {
quillValueContainer[index] = new Quill(el['editor']);
quillValueContainer[index].on('text-change', logHtmlContent);
});
Also, I don't know if this is something you need to do, but you can check if the Quill Object has already been initialized and skipping a duplication if it has, by doing:
data.filter(function(el, index){ return !quillValueContainer[index]; }).foreach(...
Or
data.forEach(function(el, index) {
if(quillValueContainer[index]) return;
quillValueContainer[index] = new Quill(el['editor']);
quillValueContainer[index].on('text-change', logHtmlContent);
});
So I have an array something like this:
var first_array = ['foo','bar','foobar'];
I am running a click function and trying to get the name of the array and loop through the array which has first as the ID name something like this
$('element').on('click',function(){
var id = $(this).attr('id');
var arr = id+"_array";
$.each(arr,function(index,value){
console.log(value);
})
})
Now the arr gives a variable name first_array and not the array. Hence the each loop fails. Is there a way to reference the array? I need to dynamically create the array variable name and get the array elements. I have also tried declaring the array globally and inside the click function but does not work.
Like Rayon Dabre said in the comments, you should use a parent object containing your first_array, and more, like that :
var parent_array = {
first_array: ['foo','bar','foobar'],
second_array: ['foo2', 'bar2', 'foobar2']
};
$('element').on('click',function(){
var id = $(this).attr('id');
var arr = parent_array[id+"_array"];
$.each(arr,function(index,value){
console.log(value);
})
});
You can put all your arrays into a javascript object or a parent array and access them by key/name like parentArr["first_array"]
I need to get a list of values from a set of element attributes and store them in an array.
Currently, I am doing this:
var ids = [];
$("my selector").each(function (idx, v) {
ids.push($(v).data("id"));
});
This seems a bit clunky. Is there a more efficient/streamlined way of doing this? Perhaps something more like this:
var ids = $("my selector").data("id");
Try using .map() along with .get() in this context,
var ids = $("my selector").map(function(){
return $(this).data("id");
}).get();
Less clunky:
$("my selector").each(function () {
ids.push($(this).data("id"));
});
By, removing idx and v, you can use $(this)
What is the cleanest way to put the source attribute string of all images within a div into an array?
I was hoping this would work -
var imageSourceArray = $("#leDiv img").attr('src');
alert(imageSourceArray[3]); //not alerting the source, boo hoo.
Do I need to loop through $("#leDiv img") and add each src string to an array individually? Or is there a more elegant way to do this?
You can use jQuery's map function which is described as:
Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
For your example:
var mySources = $('#leDiv img').map(function() {
return $(this).attr('src');
}).get();
Edit: Far more elegant solution, there's obviously still some looping involved internally:
var img_sources = $('#leDiv img').map(function(){ return $(this).attr('src') });
You will in fact need to loop over the collection and add sources individually.
var img_sources = [];
$('#leDiv img').each(function(i,e){
img_sources.push($(e).attr('src'))
})
Some background: jQuery.fn.attr() maps to jQuery.access() internally, the key part of which looks like this:
function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// setter functions omitted here …
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
}
Note the elems[0] part – only the first item in the collection is fed to the subsequent callback function (jQuery.attr() in fact) responsible for extracting the information.
var imageSourceArray = [];
$('#leDiv img').each(function(){
var src = $(this).attr("src");
imageSourceArray.push(src);
});
alert(imageSourceArray[3]);
you already have the src in a collection when you fetch the the images. It may be more efficient to not store the src attributes in another array:
$('#leDiv img').each(function(i,e){
var dosomethingwith = $(e).attr('src');
})
or you could do:
var ImageCol = $('#leDiv img');
alert(ImageCol[3].attr('src'));
I'm currently trying to create an object to be used in a JSON request, based on the controls on the page and their values.
I'm using the jQuery map() function to get the keys and values out of the controls like so
var data = $("fieldset > div.section").map(function (i, e) {
var result = {};
result[e.children[0].id.substring(3);] = e.children[1].value;
return result;
}).get();
This gets the data I'm after, but I end up with nested objects rather than an array, this looks like so
[{"ClientId":"123456"},{"ClientIdType":"5"},{"City":"Brisbane"},{"Sex":"10"},{"PostCode":"4064"},{"State":"QLD"}]
But what I want is something like
{"ClientId":"123456","ClientIdType":"5","City":"Brisbane","Sex":"10","PostCode":"4064","State":"QLD"}
Is there a way to do this in one go, or should I just iterate over the array again to flatten it?
This is a case for each() not map():
var data = {};
$("fieldset > div.section").each(function (i, e) {
data[e.children[0].id.substring(3)] = e.children[1].value;
});