Loop in javascript to append a series of divs - javascript

This is my code, but it does not work.
for (i = 0; i < 5; i++) {
$(function(){
$('.tt'+ [i]).appendTo('.td'+ [i]);
});
}
I want the result:
$('.tt1').appendTo('.td1')
$('.tt2').appendTo('.td2')
$('.tt3').appendTo('.td3')
$('.tt4').appendTo('.td4')
$('.tt5').appendTo('.td5')
Please correct me, thanks you in advance!

You have some syntax errors, try this:
for (var i = 0; i <= 5; i++) {
$('.tt'+ i).appendTo('.td'+ i);
}

As already mentioned: remove the array initialization.
If you want to iterate from 1 to 5 then do so (not var = 0, but var i = 1):
for (var i = 1; i < 6; i++) {
$('.tt'+ i).appendTo('.td'+ i);
}
Also I don't see any sense in wrapping it the appendTo call.

The 1st Thing
You will never jump into the i=5 iteration
$('.tt5').appendTo('.td5')
because your for loop
for (i = 0; i < 5; i++)
ends at i = 5
Change it to
for (i = 1; i <= 5; i++)
It starts at i=1 because your example didn't show a ".tt0"
The 2nd thing
Remote the brackets!
Change
$('.tt'+ [i]).appendTo('.td'+ [i]);
to
$('.tt'+ i).appendTo('.td'+ i);
Otherwise you will create an Array and the JS interpreter performs an unnecessary Array.toString() operation.
The 3rd thing
I think you can remove the surrounding function inside the for loop
$(function(){
...
}
Just use:
for (var i = 1; i <= 5; i++) {
$('.tt'+ i).appendTo('.td'+ i);
}
See Fiddle
http://jsfiddle.net/Spaghettirocker/knkpaczg/1/

Related

How to update all child IDs using plain JavaScript

I have a JavaScript function called resetIndex. It works fine but I want to reset all child IDs. How can I do this? Is there any method like firstChild and lastChild?
I'm new with JavaScript. Can anyone help?
I have following function:
function resetIndex(delId) {
for (var i = delId + 1; i < count; i++) {
var currentElement = document.getElementById(i);
currentElement.id = i - 1;
var update = currentElement.childNodes;
update.setAttribute('id', 'deleteLink(' + currentElement.id + ')');
}
count--;
}
You can use
node.children[0]
to get the first one, and
node.children[node.children.length - 1]
to get the last one.
Make sure to check if they exist, first.
To do something to all child-nodes, you can use a for-loop, like
for(let a = 0; a < node.children.length; a++) {
node.children[a].id = "my-new-id";
}

Short way to write a long series of if-else-if's?

How to do two variables in an if condition? Here I have few else ifs and I want a 100 else ifs! Is there a shorter way?
$(document).on('click', '.btn-next', function () {
var z = [];
var recipientsArray = z.sort();
var zDuplicate = [];
$('option:selected.exclude_global').each(function() {
z.push($(this).val())});
for (var i = 0; i < recipientsArray.length - 1; i++) {
if (recipientsArray[i + 1] == recipientsArray[i]) {
zDuplicate.push(recipientsArray[i]);
}else if(recipientsArray[i + 2] == recipientsArray[i]){
zDuplicate.push(recipientsArray[i]);
}else if(recipientsArray[i + 3] == recipientsArray[i]){
zDuplicate.push(recipientsArray[i]);
}else if(recipientsArray[i + 4] == recipientsArray[i]){
zDuplicate.push(recipientsArray[i]);
}
}
if(zDuplicate.length>>0){
alert("Global Filter Already Exists");
event.preventDefault();
}
});
Here I have few else ifs and I want a 100 else ifs! Is there a shorter way? I have a dynamic table with dynamic rows. when my table has 5 rows the code is working, but when I have more its not working.
What you're looking for is called a nested loop. You basically can write a loop within a loop. (As many as you want, actually. Though it can get ugly fast.)
Consider your loop structure:
for (var i = 0; i < recipientsArray.length - 1; i++) {
// check if recipientsArray[i] equals any other element
}
Well, that's just another loop:
for (var i = 0; i < recipientsArray.length - 1; i++) {
for (var j = i + 1; j < recipientsArray.length - 1; j++) {
if (recipientsArray[j] == recipientsArray[i]) {
zDuplicate.push(recipientsArray[i]);
break;
}
}
}
Note that there's probably a more efficient way of checking for duplicates. (Especially if the collection is sorted.) At the very least I've changed the logic so you're not re-comparing comparisons you've already made. (I did this by starting the inner loop at i + 1 instead of 1 as your logic does.)
I also think I've replicated your else if results by using a break statement. Since your else if logic basically means "once you find one, stop looking". That's what this break should do, or at least is intended to do, but you'll want to test that. If it doesn't (nesting can be confusing sometimes, which is why it should be done carefully) then you can probably make use of labels to achieve the same effect.
Ultimately, however you implement it, the concept is the same. You're asking how to iterate over multiple values in an array. That's what a loop is for.
I don't know that language. But data and control structures are data and control structures in any language.
Substitute your for loop by :
for (var i = 0; i < recipientsArray.length - 1; i++) {
for ( var j = i+1; j < recipientsArray.lenght-1; j++) {
if (recipientsArray[i] == recipientsArray[j]) {
zDuplicate.push(recipientsArray[i]);
break;
}
}
}
Thank you so much for the idea!
A small change to your code works like heaven!
for (var i = 0; i < recipientsArray.length - 1; i++) {
for (var j = 1; j < 100; j++) {
if (recipientsArray[i+j] == recipientsArray[i]) {
zDuplicate.push(recipientsArray[i]);
break;
}
}
}

javascript closure in loop

Following code is given:
var a = [ ], i = 0, j = 0;
for (i = 0; i < 5; i += 1) {
(function(c) {
a.push(function () {
console.log(c); });
})(i);
};
for (j = 0; j < 5; j += 1) { a[j](); }
Why does i always get bigger by 1 instead of staying 5? Hasn't the foor loop already been passed, so the i parameter given to the anonymous function should be 5?
If you referenced i from the inner closure then yes, you would see the result being 5 in all cases. However, you pass i by value to the outer function, which is accepted as parameter c. The value of c is then fixed to whatever i was at the moment you created the inner closure.
Consider changing the log statement:
console.log("c:" + c + " i:" + i);
You should see c going from 0 to 4 (inclusive) and i being 5 in all cases.
chhowie's answer is absolutely right (and I upvoted it), but I wanted to show you one more thing to help understand it. Your inner function works similarly to a more explicit function call like this:
var a = [ ], i = 0, j = 0;
function pushFunc(array, c) {
array.push(function () {
console.log(c);
});
}
for (i = 0; i < 5; i += 1) {
pushFunc(array, i);
}
for (j = 0; j < 5; j += 1) { a[j](); }
Which should also help you understand how c comes from the function argument, not from the for loop. Your inner function is doing exactly the same thing as this, just without an externally declared named function.

Using for loop to get for specific iteration result in javascript

I need help in somewhere in javascript
var obj = jQuery.parseJSON(data.d);
This ajax call result returns some data (around 31).
Here is an example:
obj[0] = 10, obj[1]=20 ,obj[2]=30 , obj[4]=21,obj[5]=16,obj[6]=54 here I want to get value of
obj[0] and ob[4] using for loop . And I also need to do this for obj[10] and obj[14] the difference will be 5 between the i values .
Any idea or help?
You can do something like this (a pseudo code)
int i = 0;
while(i < 31)
{
print(i);
i = i + 4;
}
If i understood, you want to skip 5 on each step:
var array = 'abcdefghijklmnopqrstuvwxyz'.split(''); // something that generates an array just to show an example
var i = 0;
for (; i < array.length;) {
console.log(i, array[i]);
i += 5;
}
see fiddle
var iterator=0;
for (i = 0; i < obj.length; i++) {
if(i == iterator){
alert(obj[iterator]);
iterator= iterator + 4;
}
}

Loop that finds a word in a string

So, i'm working on a 'for' loop that will identify my name, Andrew, and push it into an array, but there's something wrong with it
/*jshint multistr:true */
var text = ("Andrew is really awesome and Andrew should be working on the project, but there is honestly nothing for Andrew to do.");
var myName = ("Andrew");
var hits = [];
for (var i = 0; i < text.length; i ++) {
if (text[i] === "A") {
for (var j = i; i + nyName.length; i ++) {
hits.push(text[j]);
}
}
}
Also, the second loop is supposed to stop when it reaches the end of myName.
You're using JSHINT, so just read the error messages and it'll tell you exactly what's wrong.
Errors:
Line 7: for (var j = i; i + nyName.length; i ++) {
'nyName' is not defined.
Line 3: var myName = ("Andrew");
'myName' is defined but never used.
JSHINT isn't much good if you don't pay attention to what it's telling you.
Also, your inner loop looks odd.
for (var j = i; i + nyName.length; i ++) {
Seems like it'll cause an infinite loop. You're perhaps wanting j with a different condition.
You misspelled myName in your for loop syntax and typed nyName instead, so chances are the script dies as soon as it hits that line.
A typo in the for loop that wants to refer to myName would appear to be a big problem:
for (var j = i; i + nyName.length; i ++)
^
The misspelled myName isn't the only part that fails. You for loop will never end the loop because i + myName.length will always evaluate to true. You also need to increase the value of j or it will always get the character at index i.
Here's the corrected loop.
for (var i = 0; i < text.length; i ++) {
if (text[i] === "A") {
for (var j = 0; j < myName.length; i++, j++) {
hits.push(text[i]);
}
}
}

Categories

Resources