Missunderstanding append() or a treatement in Js/JQuery - javascript

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.

Related

Javascript: Traversing through array and accessing its various elements?

Essentially what I'm trying to do right now is, given some input text, I split it up by white space and display on a
div id= "animation"
Every time a button is clicked, the array should go forward one word.
This is my current attempt.
function displayText() {
var displayText = document.getElementbyID("animation");
var list = (document.getElementbyID("input").split(/[ \tn]+/);
for (var i = 0; i < list.length; i++) {
displayText.innerHTML = list.get[i];
}
}
Is my thought process somewhat correct? For whatever reason, it doesn't seem to be working.
there are multiple issues in your method
function displayText() {
var displayTextAnimation = document.getElementbyID("animation"); //keep variable name and method name different
var list = (document.getElementbyID("input").value).split(/[ \tn]+/); //use value property and observe extra bracket
for (var i = 0; i < list.length; i++) {
displayTextAnimation.innerHTML = list.charAt(i); //observe replacing get by charAt
}
}

Unable to .empty() the appended elements

state.on('change', function(){
city.empty();
$.getJSON("pincodes.JSON", function(pincodes){
var key = state.val();
for (var j= 0; j < pincodes['address'].length; j++) {
if (pincodes['address'][j]['circlename'] == key) {
temp.push(pincodes['address'][j]['regionname']);
}
}
cities = $.unique(temp);
for (var k = 0; k < cities.length; k++) {
city.append('<option>' + cities[k] + '</option>');
}
});
});
In the above state = $('#state') , the above works fine fills the cities on select "state" . But the issue is when a new state is selected the previously filled cities are also there . Even though I tried .empty on every change() .
You don't empty your temp array. So, every time this function is called, you keep appending items to your temp array.
You simply need to add the following line in your code:
state.on('change', function() {
city.empty();
temp = []; // <---
$.getJSON("pincodes.JSON", function(pincodes) {
What about cities = $.unique(temp);, it won't work.
According to jQuery.unique() documentation, this function
Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.
So, it is not a correct usage. If you get non-unique values from your JSON, you will need to use another way to get distinct values. There is a good SO article on this topic.

Appending Items from one array to each and every element of another array in Javascript

Note: I am not asking how to append data to an array!
Rather my problem is that I want to append items to each and every element of an array.
Here is a part of my code:
dataset=[];
var xpoints=["Jan","Feb","Mar","Apr","May"];
var ypoints=[10,20,30,40,50];
for (var i = 0; i < xpoints.length; i++) {
dataset.push({
x : xpoints[i],
y : parseFloat(ypoints[i])
});
}
The array so far would be as below:
dataset[0] - {x:Jan,y:10}
dataset[1] - {x:Feb,y:20}
dataset[2] - {x:Mar,y:30}
dataset[3] - {x:Apr,y:40}
dataset[4] - {x:May,y:50}
So far there is no problem...
But if now i have another array (Suppose that it is of the same length), I want to append the new array's elements into my existing array such that my output would be as follows:
var zpoints=["a","b","c","d","e"];
/*
Do something
*/
Required Output:
dataset[0] - {x:Jan,y:10,z:a}
dataset[1] - {x:Feb,y:20,z:b}
dataset[2] - {x:Mar,y:30,z:c}
dataset[3] - {x:Apr,y:40,z:d}
dataset[4] - {x:May,y:50,z:e}
If I do:
for (var i = 0; i < dataset.length; i++) {
dataset.push({
z:zpoints[i]
});
}
it would append it as different elements in the dataset array, which is not what I am looking for.
Is the required output achieveable using JavaScript? How?
What if I want to add multiple objects to the dataset array but I do not know the number of objects to be added while compiling?
Suppose that there can be multiples arrays:
z1=["a","b","c","d","e"];
z2=["l","m","n","o","p"];
z3=...
.
.
and so on.. and the number is unknown until runtime.
I want to do something like this:(invalid code)
for(var j=0;j<length;j++) //Length will be known only during runtime
for (var i = 0; i < dataset.length; i++) {
dataset[i].z[j] = zpoints[i]; //z[j] is invalid!!
}
I need to name the objects dynamically somehow. Is there a way to achieve this?
It's rather simple:
for (var i = 0; i < dataset.length; i++) {
dataset[i].z = zpoints[i];
}
A .push call will always append more entries to the array; in this case you want to modify the existing ones.
You need to simply add new property z to existing object:
var l = zpoints.length;
while(l --)
dataset[l].z = zpoints[l];

How can i generate new name in the loop?

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/

2D array with getElementsByTagName?

I am trying to access table cells in javascript using the getElementsByTagName method as shown below. Ultimately I want to compare each cell in the array to another value, and be able to change the background color of that cell according to the comparison.
var cells = document.getElementById("myTable").getElementsByTagName("tr");
for (i = 0; i < cells.length; i++)
{
cells[i] = cells[i].getElementsByTagName("td");
}
However, if I try to access cells[0][0], it returns undefined. I feel like I don't fully understand getElementsByTagName is doing... is there any hope for this method? Is there a more efficient one?
use jquery it will be simple :
var contentArray = new Array();
$('tr').each(function(indexParent) {
contentArray['row'+indexParent] = new Array();
$(this).children().each(function(indexChild) {
contentArray['row'+indexParent]['col'+indexChild] = $(this).html();
});
});
You can access any cell directly using the table element's .rows property, and the tr element's .cells property:
var myCell = myTable.rows[y].cells[x];
No need to build your own array.
So don't use .getElementsByTagName(), which returns a one-dimensional array. (Well, actually a NodeList, but you can use it like an array as long as you remember that it is live.)
If you did want to loop through all cells to compare them to some other value here's how, left to right, top to bottom using .rows and .cells:
var rows = document.getElementById("myTable").rows;
for (var y=0; y < rows.length; y++) {
for (var x=0; x < rows[y].length; x++) {
var cellAtXY = rows[y].cells[x];
cellAtXY.someProperty = something; // your code here
}
}
You need to do something like this for each row.
var row = table.getElementsByTagName('tr')[rowIndex];
var cells = row.getElementsByTagName('td');
then build your array from the contents of these variables.
Use this to get the table cells as 2D array
var tableRows = (document.getElementById("myTable")).getElementsByTagName("tr");
var cells = [];
for(var i = 0; i < tableRows.length; i++) {
cells.push(tableRows[i].getElementsByTagName("td"));
}
And now you can get any cell on your table using
cells[0][0]

Categories

Resources