How can i generate new name in the loop? - javascript

Here is my Code:
for($i=0;$i<10;$i++)
{
$elem=data;
}
Here need instead $elem get $elem1, $elem2, $elem3 depending on the $i.
Example:
If $i = 1 row $elem=data should been $elem1=data
If $i = 2 row $elem=data should been $elem1=data
$('#div1').html($elem1);
$('#div2').html($elem2);
$('#div3').html($elem3);
Tell me please how make this?
P.S.: if you do not get the idea you can ask questions

Based on your sample snippets, this code fits your purpose just fine.
var data = [1,2,3,4,5];
for(var i=0;i < data.length; i++)
{
var elem = data[i];
// other data manipulations
$('#div'+(i+1)).html(elem);
}
http://jsfiddle.net/LmvAb/

As it is JavaScript you can do what you want. Please don't ever use this over an array unless you absolutely need to. You need to use the eval() function.
$data = "worked";
for(var $i=0;$i<10;$i++){
eval('$elem' + $i + '= $data');
}
alert(eval('$elem1'));
alert(eval('$elem2'));
alert(eval('$elem5'));
JSFiddle: http://jsfiddle.net/begWG/1/

Related

Missunderstanding append() or a treatement in Js/JQuery

I need a bit of comprehension on this one pls :
Its a function to sort by price product. Only problem is that I dont get why I dont have to empty my table before appending the products
Here is a playground
This is the code
$length = $('[data-th="Prix : "]').length;
$dispo = $('.productsDispo');
$temp = 0;
for(var i = 0; i < $length; i++)
{
for(var j = i; j < $length; j++)
{
$prixI = $($dispo[i]).find($('[data-th="Prix : "]')).text().slice(0, $($dispo[i]).find($('[data-th="Prix : "]')).text().length-2);
$prixJ = $($dispo[j]).find($('[data-th="Prix : "]')).text().slice(0, $($dispo[j]).find($('[data-th="Prix : "]')).text().length-2);
if(parseInt($prixI) < parseInt($prixJ))
{
$temp = $dispo[i];
$dispo[i] = $dispo[j];
$dispo[j] = $temp;
}
}
}
for(var i = 0; i < $length; i++)
{
$('.rwd-table tbody').append($dispo[i])
}
That's because of how append works in jQuery. From docs:
If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned):
Since you do the sorting and appending manipulating the very DOM objects you selected, they are already in the table, and you basically move them inside the table with append.
jQuery's append does not make a clone of an element that you pass to it. It 'cuts' the element from its old location and 'pastes' it into a new one.
Here's a simpler example that shows this behavior, if anyone needs it illustrated.

Print data value of array

I have a array that has IDs in JavaScript:
["1649545","1649546","1649547"] etc.
And I want to print the values of this array in a URL, so something like this the foreach function of PHP does;
foreach
www.google.com/[valueofarray]
end
I know the solution could be very easy, but I just cannot manage to find it.
I made a fiddle and used a for loop this is without the use of jQuery but only javascript. I made an example array called myArray, I used .length so that javascript stops when he's been through all of the strings in the example array.
var myArray = ['12345', '123456', '1234567'];
for (var i = 0; i < myArray.length; i++) {
console.log('http://foo.com/' + myArray[i]);
// alert(myArray[i]);
}
See it work (and be sure to open your browsers console or use alert instead for viewing the output)
jsFiddle
var p='http:',a=["1649545","1649546","1649547"],u='www.google.com';for(i=0; i<a.length; ++i) console.log([p,'',u,a[i]].join('/'));
Try this:
var idArray = ["1649545","1649546","1649547"];
var url = "www.google.com/";
idArray.forEach(function(id){
console.log("http://" + url + id);
});
https://jsfiddle.net/tcmn2Lda/

jQuery .prependTo() created table causing browser to "lag"

I have a problem I am not able to fix, quite difficult to explain but I will do my best.
Basically I have created a web application (in CodeIgniter) that takes some data of an array coming from a json encoding and adds rows to a table by using the jQuery .prependTo() method in the success function.
Every row of the table contains different elements from the database (coming from the json), depending from the value of the i counter.
The code is as the following (i cut the part about the <tr> and <td> content, it's just styling)
$.ajax({
type: "get",
async: false,
....
....
success: function(data) {
var i;
var item_cost = new Array();
var item_name = new Array();
var item_code = new Array();
var item_interno = new Array();
for(i = 0; i < data.length; i++) {
item_cost[i] = data[i].cost;
item_name[i] = data[i].name;
item_code[i] = data[i].code;
item_interno[i] = data[i].codiceinterno;
var newTr = // creates the <tr>
newTr.html('//creates the <td>')
newTr.prependTo("#myTable");
}
},
I am sorry if it is a bit unclear, if you need me to update the code because I missed something important let me know and I will do it, but this code alone should explain my problem.
The application works beautifully if in the database there are just a little number of rows (for example, i = 300). They are showed and rendered correctly and I don't get any browser slowing process. But when I work with i = 4000 rows, the browser starts acting slow just like the Javascript code is too heavy to render, and i get "lag" while trying to scroll down the html table, or inputting some values in the input boxes inside the table (to later update it by clicking a button). This is my problem: I am quite sure I'm doing something wrong that is loading up too much memory, as I tested this also on very strong computers. Even totally disabling my CSS won't do the trick.
Thanks for any help you can give me, it would be really appreciated.
The problem
You are using a lot of function call inside a loop. That take a lot of juice and the more item you have, the slower it is.
To solve that, we need to reduce the number of function calls.
My suggestion
Working with native JavaScript would save on performance here. So I suggestion you use string concatenation instead of DOM manipulation methods of jQuery.
Let rework you loop. Since you want your data in a descendant order, we need to reverse the loop :
for(i = data.length; i >= 0; i--)
Then simple string concatenation to build a tr. For that you need a var outside the loop:
var myHTML = ''; //That's the one!
var i;
var item_cost = new Array();
var item_name = new Array();
var item_code = new Array();
var item_interno = new Array();
And build the tr with +=. Although, using a single line would make it faster, but less readable :
for(i = data.length; i >= 0; i--) {
item_cost[i] = data[i].cost;
item_name[i] = data[i].name;
item_code[i] = data[i].code;
item_interno[i] = data[i].codiceinterno;
myHTML += '<tr>';
myHTML += '<td>'+yourData+'</td>';//add those data here
myHTML += '<td>'+yourData+'</td>';
myHTML += '<td>'+yourData+'</td>';
myHTML += '<td>'+yourData+'</td>';
myHTML += '<td>'+yourData+'</td>';
myHTML += '</tr>';
}
Then, prepend it to your table :
var myHTML = '';
var i;
var item_cost = new Array();
var item_name = new Array();
var item_code = new Array();
var item_interno = new Array();
for(i = data.length; i >= 0; i--) {
item_cost[i] = data[i].cost;
item_name[i] = data[i].name;
item_code[i] = data[i].code;
item_interno[i] = data[i].codiceinterno;
myHTML += '<tr>';
myHTML += '<td>'+yourData+'</td>';
myHTML += '<td>'+yourData+'</td>';
myHTML += '<td>'+yourData+'</td>';
myHTML += '<td>'+yourData+'</td>';
myHTML += '<td>'+yourData+'</td>';
myHTML += '</tr>';
}
$('#myTable').prepend(myHTML);
Limitation
From my test, the string length can be 2^28 but cannot be 2^29. That make a maximum length of approx. 268,435,456 (approx. might not be the best word here since it's between 268,435,456 and 536,870,912.
If you data character count is higher than that (but let be honnest, that would be a lot of data), you might have to split you string into 2 variables.
I know this is not a real answer to your question, but...
jQuery definitely causes the lag - no wonder. But - whether you choose jQuery to build the table or you just concatenate HTML - let's agree on that: 4000 rows is definitely a lot of data. Too much data? I would say: 200 already is. If we go thousands, the question pops up: why? Is there any application-related reason you really need to retrieve such a big number of records at once? Some of them will probably never be read.
Why not try an ajax-based lazy load approach? Loading 50-record portions every time would seem more robust IMO, and would definitely be a better UX.
My two cents: Why don't retrieve the rows composed from the server instead of making the client work to compound it? You could even cache it. The only thing would be that you'll have more traffic, but in the browser it'll go smoother
UPDATE
To achieve it, you can make your method to distinguish between ajax input or not, and show only $tbody, or the whole table according to it. It would be something like:
$tbody = $this->load->view( 'view_with_oly_tbody', $data, true );
if ( $this->input->is_ajax_request() ) {
return $tbody;
} else {
$data['tbody'] = $tbody;
$this->load->view('your_view_with_table_with_tbody_as_var', $data);
}
Note: Code above will vary according to your views, controller, if you have json in your AJAX or not, write the return in other part, etc. Code above is just for clarify my point with CI.
Ah! and you'll have to manage the answer in the client to append/prepend/substitute the body of the table.

parsing a json in loop where element names change

I'm parsing a JSON response which isn't set up the best, in my opinion. Here is the actual response:
[
{"challenge_id":"39029"},
{"song1_id":"198","name":"PRAY","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/TAKE_THAT_-_PRAY.mp3"},
{"song2_id":"251","name":"THE TEARS OF A CLOWN","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/SMOKEY_ROBINSON_-_THE_TEARS_OF_A_CLOWN.mp3"},
{"song3_id":"11","name":"WONDERFUL TONIGHT","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/ERIC_CLAPTON_-_WONDERFUL_TONIGHT.mp3"},
{"song4_id":"288","name":"THE NAME OF THE GAME","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/ABBA_-_THE_NAME_OF_THE_GAME.mp3"},
{"song5_id":"159","name":"I'M EVERY WOMAN","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/CHAKA_KHAN_-_I'M_EVERY_WOMAN.mp3"},
{"status":"ok"}
]
and here was my attempt at parsing it:
var challenge_Songs = JSON.parse(this.responseText);
for(var i = 1; i<challenge_Songs.length-1; i++){
challengeSongs[i-1] = challenge_Songs[i].url;
challengeTitles[i-1] = challenge_Songs[i].name;
voteSongIds[i-1]= challenge_Songs.song[i]_id;
}
My problem is with obtaining what I have set up as voteSongIds, as the name changes within every iteration of the loop. What I have tried above is causing a run time error. If I comment the line with votesongids, everything works. How should I parse the parse JSON?! Any help appreciated :) I'm using titanium, but for these purposes, it's just javascript!
Is this the result you looking for?
var challenge_Songs = [
{"challenge_id":"39029"},
{"song1_id":"198","name":"PRAY","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/TAKE_THAT_-_PRAY.mp3"},
{"song2_id":"251","name":"THE TEARS OF A CLOWN","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/SMOKEY_ROBINSON_-_THE_TEARS_OF_A_CLOWN.mp3"},{"song3_id":"11","name":"WONDERFUL TONIGHT","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/ERIC_CLAPTON_-_WONDERFUL_TONIGHT.mp3"},
{"song4_id":"288","name":"THE NAME OF THE GAME","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/ABBA_-_THE_NAME_OF_THE_GAME.mp3"},
{"song5_id":"159","name":"I'M EVERY WOMAN","url":"https:\/\/s3-eu-west-1.amazonaws.com\/test\/CHAKA_KHAN_-_I'M_EVERY_WOMAN.mp3"},{"status":"ok"}]
var challengeTitles=[],
challengeSongs = [],
voteSongIds=[];
for(var i = 1; i < challenge_Songs.length-1; i++){
challengeTitles.push(challenge_Songs[i]['name']);
challengeSongs.push(challenge_Songs[i]['url']);
voteSongIds.push(challenge_Songs[i]['song'+ i +'_id'])
}
console.log(challengeTitles);
console.log(challengeSongs);
console.log(voteSongIds);
Try the following code. This will work perfect whatever the key or value
for(var i = 0; i<challenge_Songs.length; i++){
for(key in challenge_Songs[i]){
console.log("\n key=>" + key + " : value=> " + challenge_Songs[i][key]);
}
console.log("\n");
}
It will display you all the keys and correspondent value in more simple way

How to remove a null element in jquery?

I have an application in which i am storing values in localstorage. By default my first value is null due to which i am getting error to run the code so i want to remove the first element and continue the processes. can anyone please help me how to remove first element from list?
Piece of my code is below:
var str = localStorage.getItem("appidlist");
var mySplitResult = str.split(",");
for(var i = 0; i < mySplitResult.length; i++) {
if (.....) {
.
.
}
}
where str returns null,1,2,3,.....
I hope my question is clear can anybody help me.
This should also work:
var str = localStorage.getItem("appidlist");
var mySplitResult = str.split(",");
mySplitResult.splice(0, 1);
You can use .shift().
mySplitResult.shift()
Instead of uing the shift() function, I would suggest you to create a function that return a new clean array. This will solve even the case where there are more than one (and in any postion) null value.
You can use this solution
This should do the trick:
var str = localStorage.getItem("appidlist");
var mySplitResult = str.split(",").splice(1); // Remove the first item.
for(var i = 0; i < mySplitResult.length; i++) {
// Stuff
}

Categories

Resources