Using variable inside array.push() in jquery - javascript

I have a for loop in my jquery script
var images[];
for(i=0;i<$('#imageHolder div').length;i++)
{
images.push($('#imageHolder div:eq( i )').attr('alt'));
console.log($('#imageHolder div:eq(i )').attr('alt'));
}
I am not able to add the elements to the array and the console.log says undefined in the console.
What is my possible error and how that can be corrected?

jQuery has useful method for this task, called $.fn.map:
var images = $('#imageHolder div').map(function() {
return $(this).attr('alt');
}).get();
Will produce an array of images alt attributes.

You have a typo:
images.push($('#imageHolder div:eq(' + i + ')').attr('alt'));
you need to concat i ^^^^
By the way, don't select your element every time in the for
var divs = $('#imageHolder div');
for(i=0; i < divs.length; i++)

i is a variable so need to use concatenation
$('#imageHolder div:eq('+ i + ')').attr('alt')
A more efficient way is to use .map(), in your case you are evaluating the selector many times which is not a optimal way
var images = $('#imageHolder div').map(function () {
return $(this).attr('alt')
}).get()

Related

How to get value from text box by name which is dynamic

I need a value of text box for that I am using document.getElementsByName("elemntName") but the problem is the the name itself is dynamic, something like below.
for(temp = 0 ; temp < arracid.length ; temp++){
cell1=mynewrow.insertCell(4);
cell1.innerHTML="<input type='hidden' name='ACID"+index+"' class='tblrows' id='ACID"+index+"' value='"+arracid[temp]+"'>";
index++;
}
When I tried var acidCount = document.getElementsByName('ACID') its not working and I tried
var acidCount = document.getElementsByName('ACID"+index+"') still not working
For every loop the name is changing like ACID1,ACID2 etc.. can anyone help me how to get the value of this text box?
Since you are already assigning an ID to your inputs, it's recommended to use getElementsById which is faster than getElementsByName (and more accurate because the IDs are supposed to be unique, while the names don't have to be). Try this:
var acidCount = document.getElementById("ACID" + index);
If you still want to use getElementsByName, try this:
var acidCount = document.getElementsByName("ACID" + index);
But remember that getElementsByName returns a list of elements, but the list has only one element, because your names are unique. If you want to get that element in the list, you can use it's index like this:
var acidCount = document.getElementsByName("ACID" + index)[0];
Alternatively, if you want to get the list of all your inputs, first remove the index from the name:
cell1.innerHTML="<input type='hidden' name='ACID' class='tblrows' id='ACID"+index+"' value='"+arracid[temp]+"'>";
Then use:
var acidCount = document.getElementsByName("ACID");
Note: all the above return the DOM element(s). If you're only interested in the value, use the value property:
var acidCount = document.getElementById("ACID" + index).value;
or
var acidCount = document.getElementsByName("ACID" + index)[0].value;
(This is a jquery solution, since the question was initially tagged with jQuery)
You can use the selector of input elements with name starting with ^= ACID:
$("input[name^=ACID]").each(function(){
console.log($(this).val());
});
Issue is with single quoutes and double quotes :
var acidCount = document.getElementsByName("ACID"+index)
Since there can be more than one element with same name, so we need to get first element with that name, I have corrected your query check this, it will work.
var acidCount = document.getElementsByName('ACID'+index)[0].value
Try using wildcard * in the selector which will return all matched elements
document.querySelectorAll('[id*=ACID]')
You can try using class name.
$(document).find(".tblrows").each(function(){
console.log($(this).val());
});
Since you are naming your elements 'ACID' + index, you can utilize the querySelector method as follows:
for (var i=0; i < arracid.length; i++) {
var $el = document.querySelector('#ACID' + i));
}

Javascript for each loop

I'm trying to write this:
$('.circle_div').each(function(){
var $this = $(this),
thisWidth = $this.width();
$this.css('height', thisWidth + 'px');
});
in javascript like this:
var circle_div = document.getElementsByClassName('circle_div');
for (el in circle_div){
var thisWidth = el.style.width;
el.style.height = thisWidth + "px";
}
I also tried for...of and for each, and a regular for loop incrementing var i. The jquery function works but the javascript doesn't. Any idea what I'm doing wrong?
Eeeck. Never use for/in to iterate elements of an array or array-like object (doing so will include other iterable properties in addition to just the array elements).
Plus el in your loop is the index, not the value. You have to use circle_div[index] to get the element from the nodeList. But, you MUST switch to a traditional for loop, not for/in.
var circle_div = document.getElementsByClassName('circle_div');
for (var i = 0; i < circle_div.length; i++) {
var item = circle_div[i];
item.style.height = item.style.width;
}
You also have to remove the + "px" because the units are already there in plain javascript.
For more details on using for loop with document.getElementsByClassName() (including ES6 info), see this other answer: For loop for HTMLCollection elements.
If you convert the NodeList object that returns getElementsByCLassName to a regular array, you can use the Array.prototype.forEach method on it:
// Get the divs, and convert the NodeList to a regular array.
var circle_div = [].slice.call(document.getElementsByClassName('circle_div'), 0);
circle_div.forEach(function (el) {
el.style.height = el.clientWidth + "px";
});
This way looks more similar to your jquery code.
Check the fiddle: http://jsfiddle.net/7ew39phu/
Edit: I realize I should have used clientWidth, instead of style.width. The reason is that style properties seem to be only available if they were set using JavaScript, not if they were set using an css sylesheet.
Anyway, I fixed the code.
var circle_div = document.getElementsByClassName('circle_div');
for (var i=0,l=circle_div.length; i<l; i++){
circle_div[i].style.height = circle_div[i].style.width;
}

Count length of an array and create the same amount of HTML elements with JS/jQuery

Is it possible to query the length of an array and then use JS/jQuery to create the same amount of new HTML elements client side?
The code I have for the array is:
var psC1 = [
'item1',
'item2',
'item3'
];
alert(psC1.length);
Which will alert that there's 3 items in the array. I now want to create three iframes on the page, and index the array into the src attribute of each element.
The code I'd use to insert the src of the iframes using the array would be:
$('.test-iframe').each(function() {
$(this).attr('src', psC1[$(this).index()]);
});
What I'm struggling with is after counting the array, is creating three iframes with JS/jQuery.
To create an iframe with jQuery, you use the $ function (or jQuery in no-conflict mode):
$("<iframe>").appendTo(document.body);
Of course, you don't have to append to body, you can put the iframe wherever you need it.
In your case, perhaps something like this:
$.each(psC1, function(index, value) {
$("<iframe>").attr("src", value).appendTo(document.body);
});
$.each loops through the array entries.
for (var x = 0; x < psC1.length; x++) {
$("<iframe>", {'src': x}).appendTo("body");
}
The $("<iframe>") syntax creates the element. .appendTo adds it to the DOM. Note that this will just create iframes with source of "0," "1," and "2," so you probably want something like '/some/path/?page=' + x as the src.
Note that you could also use $.each instead of a normal for loop, but it's more expensive and, in my opinion, unnecessary.
You could use a loop to create the HTML
var iframeHTML = "";
for (int i = 0; i < count; i++)
{
iframeHTML += "<iframe class='test-iframe'></iframe>";
}
then append the HTMLString where you want.
You can make this cleaner with jQuery.map:
$('body').append($(psC1).map(function (i, src) {
return $('<iframe>').attr('src', src);
}).get());

How to automatically generate input-array index in jQuery?

For example, I have such HTML:
<input name="someinput[]">
I made a function to clone/remove this input but now I want to assign indexes to name dynamically - when I make an element clones, its new names should be someinput[1], someinput[2] etc. - how to make this?
You could just replace [] with [index] using the attr callback:
var i = 0;
$('button').click(function(){
$('input:first').clone().attr('name',function(a,e){
i++;
return e.replace("[]","["+i+"]");
}).insertAfter($('input:last'));
});
example: http://jsfiddle.net/niklasvh/c9G7c/
Keep the index of the next input in a global variable, and then use that in your cloning function. Is that what you do?
var source = $('#source')
var copy = source.clone().attr('name', 'some[' + index + ']')
$('body').append(copy);

jQuery .each help, I want to trim() all the strings in an array

I'm splitting a string into an array, then I want to remove the white space around each element. I'm using jQuery. I'm able to do this successfully with 2 arrays but I know it's not correct. How do I loop thru an array and trim each element so the elements keep that change. Thanks for any tips. Here is my working code using two array. Please show me the correct way to do this.
var arVeh = vehicleText.split("|");
var cleanArry = new Array();
$.each(arVeh, function (idx, val) {
cleanArry.push($.trim(this));
});
Cheers,
~ck in San Diego
You don't even really need the idx or val parameters. This appears to work on jsFiddle:
var cleanVehicles = [];
$.each(vehicleText.split("|"), function(){
cleanVehicles.push($.trim(this));
});
EDIT: Now that I've seen what you're really after, try using map:
var cleanVehicles = $.map(vehicleText.split("|"), $.trim);
I'm going to suggest not using the overhead of jQuery for a simple for-loop...
var arVeh = vehicleText.split("|");
for (var i = 0, l = arVeh.length; i < l; ++i) {
arVeh[i] = $.trim(arVeh[i]);
});
Alternatively, get rid of the whitespace from the beginning, and avoid the need for another loop at all.
var arVeh = $.trim(vehicleText).split(/\s*\|\s*/);
Without 'creating' an array in the javascript code (an array will nevertheless be created in memory)
vehicles = $.map(vehicleText.split("|"), function(e,i) { return $.trim(e) });
var my_arr = [' cats', 'dogs ', ' what '];
$.each(my_arr, function (id, val) {
my_arr[id] = $.trim(val);
});
console.log(my_arr);
This will trim the value and set it to the indexed item.
You don't have to use JQuery. Here is your vanilla solution:
testArray.map(Function.prototype.call, String.prototype.trim);
Function.prototype.call calls trim() on each of the elements of the testArray. As simple as that!
Could you not just do this?
var arVeh = vehicleText.split("|");
$.each(arVeh, function (idx, val) {
arVeh[idx] = $.trim(this);
});
//a simple function
function trimArray(dirtyArray){
$.map(dirtyArray.split("|"), function(idx, val){
return $.trim(this);
});
}
trimArray(vehicleArray);
should do the trick
Or you could use some of the awesome power of javascript and use array.prototype. I'm still a little new at using the .prototype of any object... so this isnt guaranteed to work (but it certainly can be done).
Array.prototype.trim = function (){
$.map(dirtyArray.split("|"), function(idx, val){
return $.trim(this);
});
}
someArray.trim()
You need these two jQuery functions:
1.) iterate through array element with ability to edit items:
http://api.jquery.com/jquery.map/
2.) remove blank spaces from beginning and end of a string:
http://api.jquery.com/jQuery.trim/
Use them this way:
array = $.map(array, function(value) { return value.trim();});
Check this JSFiddle:
https://jsfiddle.net/L00eyL4x/49/

Categories