jQuery getting value from dynamic array - javascript

I have an array with divs ids (in my case its all divs ID values od parent div (#area) ):
jQuery.fn.getIdArray = function () {
var ret = [];
$('[id]', this).each(function () {
ret.push(this.id);
});
return ret;
};
var array = $("#area").getIdArray();
I need to get an array field value, something like this:
var lef = $("#array".[0]).css("left");

Taking a wild swing at it (see my comment on the question):
var array = $("#area").getIdArray();
var lef=$("#" + array[0]).css("left");
That assumes that getIdArray returns an array of strings, where each string is an id value for a DOM element, and that you want to get the left value for the first of those elements.
So for instance, if the array comes back as:
["foo", "bar", "charlie"]
then the selector created by "#" + array[0] is #foo, so you end up getting the left value for the foo element.

If you have an actual JS array within your variable array just use bracket notation to access each individual ID.
// I have the # before-hand since I'm assuming you have just the ID name
var lef = $('#' + array[0]) // this will access the 1st one in the array

I think you are looking for this :
var divYouWantToChange = $("#"+array[0]);

I try to formulate this as an answer because getIdArray is not a jquery function and we don't know what it does. If you'd like to apply a custom filter to the $("#area") collection you can do so using filter. This will return a jquery object where you can get the .css("left") from.
If you'd like to save both the id's and the left property you can do so with the following code:
var objects=[];
$("#area").filter(function(){
$this=$(this);//cache the object
objects.push({id:$this.attr("id"),
left:$this.css("left")
};
});
console.log(objects);

Related

What am I missing in the jQuery .each() function?

I have this function that I am trying to figure out/fix and can't seem to pinpoint the issue / can't figure out a way to get it working.
Basically my CMS is spitting certain hrefs that I would like to:
Part 1) change the targeted href URL
Part 2) change the button's text
Right now I only have 2 instances of this type of button, so here's what is printing out in my console:
Part 1) for this part I get the correct urls without the characters i want to strip out.
Part 2) two instances of the button's text (See All) followed by the correct variable of btnParent for the first button and then the second button and finally one instance of "Products".
My issue is, I can't figure out how to:
Part 1) send back the stripped URL to its respective button's href as an each function.
Part 2) Have the each() function print out the new text as "See All + BLAH + Products" for each instance, and then append the new text to the respective button.
Here is the code:
function viewMoreBtn() {
var btnMain = $("li:contains('See All')");
var btnText = $("li:contains('See All')").text();
var btnParent = $("li:contains('See All')").parent('ul').prev('li').text();
// PART 1 - STRIP LINK URL OF -_-// CHARACTERS
$.each(btnMain, function(i, v) {
v = $(this).find('a').attr('href').replace('-_-//', '');
console.log(v);
});
// PART 2 - ADD LABEL TO HTML TEXT OF BTN
$.each(btnMain, function(index, value) {
value = (btnText + btnParent + 'Products');
$(btnMain).text(value);
console.log(value);
});
}
viewMoreBtn();
Thank you.
jQuery objects, as return by $(...) have a each method already on them. The element is passed as the this context. You could use that further with jQuery to act on the objects in an scoped context. Basically, you have the right code, just in the wrong scope.
Part 1
btnMain.each(function() {
var $li = $(this);
var $a = $li.find('a');
var desiredUrl = $a.attr('href').replace('-_-//', '');
$a.attr('href', desiredUrl);
});
Part 2
btnMain.each(function() {
var $li = $(this);
var btnText = $li.text();
varbtnParent = $li.parent('ul').prev('li').text();
value = (btnText + btnParent + 'Products');
console.log(value);
$li.find('a').text(value);
});
See #Zequ's answer for the iteration over the each() function in the returned btnMain.
This is how $.each( obj, function( key, value ) works: you iterate over btnMain, and for each iteration of $.each(), the function assigns the index of the iteration to i and the value of btnMain at that index to v.
$.each(btnMain, function(i, v) {
//v = $(this).find('a').attr('href').replace('-_-//', '');
console.log(i); // I am the index of $.each() iterator
console.log(v); // I am the node from the btnMain array
// I don't know if this is right without seeing your HTML, but it seems like what you want
v.find('a').attr('href').replace('-_-//', '');
});
The second $.each() follows the same pattern.
If I understood correctly, you're confusing your variables.
$.each is a function for each element of the array/object being passed. It gives you a index and the element, check the reference
In part 1, you're defining v as the string you want, you're not changing the element at all,you need something like this:
$.each(btnMain, function() {
// you're saying you got the correct URLs, so the only thing you need to do is to change the element afterwards
var element = $(this).find('a');
v = element.attr('href').replace('-_-//', '');
element.attr('href', v);
});`
Also you could use btnMain.each instead of $.each
In part 2, you are changing the value variable (it's actually the element you're iterating over), to the string you want, then you follow it by trying to change btnMain's text. This is wrong, from what I understood, btnMain is an array of two elements you can't change it's text. You should change the element's value (that you are calling value). It would be something like that
$.each(btnMain, function(index, element){
// I think this is the time you want to define the btnParent, relative to the element
var btnParent = element.parent('ul').prev('li').text();
var value = (btnText + btnParent + 'Products');
element.text(value);
}
I THINK this is what you need.
Also you could append both parts into one, since both are iterating over btnMain

Get only word part of an id/name

I have a div element with lots of descendent's elements, all with ids in the form "word1", for a simple example: id="moviment1" or id="type1".
I need to get only the written part of these ids (moviment or type), in order to concatenate their names with a increment of 1 (id="moviment2" or id="type2").
$clone.find('*').each(function() {
var id = $(this).prop('id');
var num = parseInt( $(this).prop("id").match(/\d+/g), 10 ) +1;
$(this).prop('id', id+num);
});
The way it is, I always get ids like id="moviment12". I already tried:
var id = $(this).prop('id').replace(/\d+/g, '');
or
var id = $(this).prop('id').match(/\w+/);
But I always get errors like "cannot read property 'replace'/'match' of undefined". So, what am I doing wrong? Any other ideas? Thank you very much!
Ideally you should use a template. Traversing and modifying parsed elements makes your code slow and hard to maintain.
If you want to increment the number part of the IDs by 1 you can use the replace method callback function:
$clone.find('[id]').prop('id', function(_, id) {
// Assuming `id` is `test_25_segment`
return id.replace(/(\d+)/, function(num) {
// |
// --- is 25
return +num + 1;
// |
// --- parses the matching string into integer
});
});
Here is a demo using the above snippet.
Easiest way, you could just add those values as data-attr:
<div id="type1" data-id="1" data-text="type"></div>
So you can easily get them separated just using .data('id') and .data('text').
You may select the elements by this way:
var all = [].filter.call(document.querySelectorAll('[id*=type]'), function(el) {
return (/\btype\d+\b/).test(el.id);
});
and then you can change the ids using methods like replace()
Try this...
var onlyAlphabets = id.split(/(\d)/)[0];

access javascript array element by JSON object key

I have an array that looks like this
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}]
I would like to be able to access the Count property of a particular object via the Zip property so that I can increment the count when I get another zip that matches. I was hoping something like this but it's not quite right (This would be in a loop)
Zips[rows[i].Zipcode].Count
I know that's not right and am hoping that there is a solution without looping through the result set every time?
Thanks
I know that's not right and am hoping that there is a solution without
looping through the result set every time?
No, you're gonna have to loop and find the appropriate value which meets your criteria. Alternatively you could use the filter method:
var filteredZips = Zips.filter(function(element) {
return element.Zip == 92880;
});
if (filteredZips.length > 0) {
// we have found a corresponding element
var count = filteredZips[0].count;
}
If you had designed your object in a different manner:
var zips = {"92880": 1, "91710": 3, "92672": 0 };
then you could have directly accessed the Count:
var count = zips["92880"];
In the current form, you can not access an element by its ZIP-code without a loop.
You could transform your array to an object of this form:
var Zips = { 92880: 1, 91710: 3 }; // etc.
Then you can access it by
Zips[rows[i].Zipcode]
To transform from array to object you could use this
var ZipsObj = {};
for( var i=Zips.length; i--; ) {
ZipsObj[ Zips[i].Zip ] = Zips[i].Count;
}
Couple of mistakes in your code.
Your array is collection of objects
You can access objects with their property name and not property value i.e Zips[0]['Zip'] is correct, or by object notation Zips[0].Zip.
If you want to find the value you have to loop
If you want to keep the format of the array Zips and its elements
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}];
var MappedZips = {}; // first of all build hash by Zip
for (var i = 0; i < Zips.length; i++) {
MappedZips[Zips[i].Zip] = Zips[i];
}
MappedZips is {"92880": {Zip: 92880, Count:1}, "91710": {Zip:91710, Count:3}, "92672": {Zip:92672, Count:0}}
// then you can get Count by O(1)
alert(MappedZips[92880].Count);
// or can change data by O(1)
MappedZips[92880].Count++;
alert(MappedZips[92880].Count);
jsFiddle example
function getZip(zips, zipNumber) {
var answer = null;
zips.forEach(function(zip){
if (zip.Zip === zipNumber) answer = zip;
});
return answer;
}
This function returns the zip object with the Zip property equal to zipNumber, or null if none exists.
did you try this?
Zips[i].Zip.Count

Get inputs value and separated by "|"

I have inputs and I need to get values and separated by "|" symbol.
My input:
Output what I need:
00:00|00:00|00:00
My code is :
(and it's not working)
var timesArray = $('table').find('input');
var times = timesArray.val();
$('.alltimes').val(times);
Given that .val returns the value of each element (whatever input type it is in your screenshot), then you can use .map: http://jsfiddle.net/RrCYD/.
var values = $("input").map(function() {
return $(this).val(); // map each element to its value
}).get().join("|"); // get real array and join
See comments in code:
// Create an array to store the input values
var inputValues = [];
// Iterate over input's and store their value in the array
$('table').find('input').each(function () {
inputValues.push(this.value);
});
// Create pipe=delimited string from array of values
var delimitedInputValues = inputValues.join("|");
Additional Information
MDN - array.join
jQuery - .each()

Associative style arrays in Javascript?

I'm trying to assign an object in the style of an associate array in JS but it's failing, saying 'task.id' is undefined. Why is this?
var response = Object();
$('.task-list').each(function() {
response[this.id][$('#' + this.id).sortable('toArray')];
});
You are referencing the object as a two dimensional array.
You should do it more like this:
var response = {};
$(".task-list").each(function () {
response[this.id] = $(this).sortable('toArray');
}
Also, when you say the error is "task.id is undefined", do you mean "this.id is undefined"? If you are selecting elements based on class, they may not have an explicit id.
<span class="task-list">myTask</span>
You may want to include an id:
<span class="task-list" id="myTask">myTask</span>
You are trying to access a property that you haven't created yet. Although it's not actually clear what you are trying to do from your example. I'm assuming you want to set the value of response[this.id] to $('#' + this.id).sortable('toArray')?
Try this instead:
var response = {};
$('.task-list').each(function() {
response[this.id] = $(this).sortable('toArray');
});
Also changed it to use $(this) instead of $('#' + this.id) as it's cleaner imo.

Categories

Resources