How to give ID to row dynamically? - javascript

I am generated a row dynamically in this fiddle.I want to give ID to that row .And Display that on header can we give this.I want to give ID like this 1,2,3...
But there is a problem Is that That rows are nested So can we give ID to inner row also .IF there is an row inside first his ID 1_1, 1_2....If some element is inside 1_1.then it ID id 1_1_1....So on
Can we do this ?
function buildNav(nodes) {
var result = '<div data-role="collapsible-set" id="stuff">';
var i = 0, len = nodes.length;
for(; i < len; i++) {
result += "<div data-role='collapsible' data-content-theme='c'><h3>test</h3>"+content;
if(nodes[i].testCaseList) {
result += buildNav(nodes[i].testCaseList) + "</div>";
}
result += "</div>";
}
return result + "</div>";
}
$(function(){
$('#test ').html(buildNav(testData.testCaseList)).trigger('create');
});

Try passing the value of the current level to your function and prepend it to the id.
function buildNav(nodes, level) {
var result = '<div data-role="collapsible-set" id="' + level + '">';
var i = 0, len = nodes.length;
for(; i < len; i++) {
var id = level + '_' + i;
result += "<div data-role='collapsible' data-content-theme='c'><h3>test</h3>"+content;
if(nodes[i].testCaseList) {
result += buildNav(nodes[i].testCaseList, id) + "</div>";
}
result += "</div>";
}
return result + "</div>";
}
$(function(){
$('#test ').html(buildNav(testData.testCaseList, 0)).trigger('create');
});

Related

How do I apply code to a dynamically created element

The following code works only if the table is already present in the document upon page load. I however want it to apply on a dynamically created table.
Can this be done?
var colNumber=22
for (var i=0; i<colNumber; i++)
{
var thWidth=$("#tbl").find("th:eq("+i+")").width();
var tdWidth=$("#tbl").find("td:eq("+i+")").width();
if (thWidth<tdWidth)
$("#tbl").find("th:eq("+i+")").width(tdWidth);
else
$("#tbl").find("td:eq("+i+")").width(thWidth);
}
The table is created in the following way:
function loadFile(event){
alasql('SELECT * FROM FILE(?,{headers:false})',[event],function(data){
var keys = [];
for (var i = 0; i < data.length; i++) {
for (var categoryid in data[i]) {
var category = data[i][categoryid];
keys.push(categoryid);
}
}
keysConverted = keys.map(foo);
var vMin = Math.min.apply(null, keysConverted);
var vMax = Math.max.apply(null, keysConverted);
var start = vMin-1
var ColNeeded = vMax - vMin+1;
var arrExcel2Table = '<table id="tbl">';
for (var i = 0; i < data.length; i++){
arrExcel2Table = arrExcel2Table + '<tr>';
for (var j = 0; j < ColNeeded; j++){
cellValue = data[i][number2Letter(j+start)];
if (typeof cellValue === "undefined"){
cellValue = '';
}
arrExcel2Table = arrExcel2Table + '<td>' + cellValue + '</td>';
}
arrExcel2Table = arrExcel2Table + '</tr>';
}
arrExcel2Table = arrExcel2Table + '</table>';
document.getElementById('excel_table').innerHTML = arrExcel2Table;
});
}
Create a function you want to run and add an event from the dynamic element. For example
arrExcel2Table = arrExcel2Table + '<td>' + cellValue + '</td>';
can be replaced by
arrExcel2Table = arrExcel2Table + '<td onclick="myFunction();">' + cellValue + '</td>';
Above code will call the function you created
myFunction() {
alert();
}
Just create your table, then apply whatever code you want to it :
$('#excel_table').html(arrExcel2Table);
adjustWidth()
function adjustWidth(){
var $tbl = $("#tbl"); // And cache your jQuery objects!! Massive performance boost
for (var i=0; i<colNumber; i++)
{
var $th = $tbl.find("th:eq("+i+")"),
$td = $tbl.find("td:eq("+i+")"),
thWidth = $th.width(),
tdWidth = $td.width();
if (thWidth<tdWidth)
$th.width(tdWidth);
else
$td.width(thWidth);
}
}

how to display image through XML to html

Hie i am practicing XML , Javascript. I want to display image for each animal in a row. But my main problem arises uneven nesting in images . Some have two images while some have 4. I have XML File as follows:
<zoo>
<animal>
<common_name>Elephant</common_name>
<images>
<image>elephant13.jpg</image>
</images>
</animal>
<animal>
<common_name>Emu</common_name>
<images>
<image>emu12.jpg</image>
<image>emu26.jpg</image>
<image>emu23.jpg</image>
</images>
</animal>
<animal>
<common_name>Lion</common_name>
<images>
<image>lion51.jpg</image>
<image>lion46.jpg</image>
</images>
</animal>
<zoo>`
My javascript for img is :
for(var y = 0; y < noOfImages ; y++)
{
if (images)
{
images.src ="images/" + zooRoot.getElementsByTagName("image")[i].firstChild.nodeValue;
ul.appendChild(images);
}
}
Try this. This get's the document node of xml and queries for images from it. Once you have the array, you iterate over it and get the inner text from the node.
var xmlimages = xml.getElementsByTagName('image');
for(var i=0; i< xmlimages.length; i++) {
images.src = "images/" + xmlimages[i].innerHTML.trim(); // trim used to remove all the white space from text that you get when you use innerHTML
}
Please insert loop on node:
for(var y = 0; y < noOfImages ; y++)
{
if (images)
{
var imgData = zooRoot.getElementsByTagName("image");
for (i = 0; i <imgData.length; i++) {
images.src ="images/" + imgData[i].firstChild.nodeValue;
ul.appendChild(images);
}
}
}
Try to get Animal as an object, then create a HTMLstring and insert it in node;
var animalsNode = zooRoot.getElementsByTagName('animal');
var animals = [];
for(var i=0; i<animalsNode.length; i++){
var animalName = animalsNode[i].getElementsByTagName("common_name").innerHTML;
var animalImageNodes = animalsNode[i].getElementsByTagName("image");
var animalImages = [];
//will store image paths into animalImages
for(var j=0; j<animalImageNodes.length; j++){
animalImages.push("image/" + animalImageNodes.innerHTML);
}
animals.push({
common_name: animalName,
images: animalImages //array of image urls
})
}
var animalsHTML = function(animals){
//lets cereate string with "html table"
var animalsHtml = "<table>";
for(var i=0; i<animals.length; i++){
animalsHtml += "<tr>";
animalsHtml += "<td>" + animals[i].name + "</td>"
+ "<td><img src='" + animals[i].images[0] + "' /></td>";
animalsHtml += "</tr>";
}
animalsHtml += "</table>";
return animalsHtml;
}
tableNode.innerHTML = animalsHTML(animals);
or you can define animal array more functional way =)
var animals = zooRoot.getElementsByTagName('animal').map(function(animalNode){
return {
common_name: animalNode.getElementsByTagName('common_name')[0].innerHTML,
images: animalNode.getElementsByTagName('image').map(function(imageNode){
return "image/" + imageNode.innerHTML;
})
};
});
//and more js style of draw-function
var animalsHTML = function(animals){
return "<table>" + animals.reduce(function(curr, next){
return curr + "<tr><td>" + next.name + "</td>"
+ "<td>"
+ next.images.reduce(function(c, n){
return c + "<img src='" + n "' />"
},'')
+ "</td>"
+ "</tr>";
}, '') + "</table>";
}
tableNode.innerHTML = animalsHTML(animals);
I didn't test it, but it should work.

JavaScript function performed on 6 id's at a time (return after 6 calls ?)

I am wondering if there is a function I can use so that I can seperate data being called into groups of 6.
here is the long form of the code
var currentResults;
function init() {
getProducts();
}
function getProducts() {
$.ajax({
url:"php/products.php",
dataType: "json",
data: { public: true },
success:function(result){
processResults(result);
}
});
}
function processResults(results) {
currentResults = null;
if (!results && !results.products)
return;
currentResults = results.products;
for (var i = 0; i < results.products.length; i++) {
processResult(results.products[i]);
}
$(".galleryitem").click(handleThumbnailClick);
}
function processResult(result) {
var newDiv = '<div id="galleryitem' + result.id + '" class="galleryitem">';
newDiv += '<div class="imageHover" style="background: ' + result.color + '"> </div>';
newDiv += '<img class="galleryImage" src="' + encodeImagePath(result.thumbnail) + '" />';
if (result.artist)
newDiv += '<div class="imageArtist">' + result.artist + '</div>';
newDiv += '< /div>';
$('#gallery').append(newDiv);
}
i would like the function to be able to sort the images to groups of 6, something like this... (see areas at bottom with ***'s)
function processResult(result) {
var newDiv = '<div id="galleryitem' + result.id + '" class="galleryitem">';
newDiv += '<div class="imageHover" style="background: ' + result.color + '"> </div>';
newDiv += '<img class="galleryImage" src="' + encodeImagePath(result.thumbnail) + '" />';
if ***(!!first 6 called!!)***
newDiv += '<div class="imageArtist">' + result.artist + '</div>';
newDiv += '< /div>';
$('#galleryfirst').append(newDiv);
if ***(!!second 6 called!!)***
newDiv += '<div class="imageArtist">' + result.artist + '</div>';
newDiv += '< /div>';
$('#gallerysecond').append(newDiv);
}
Is doing something like this possible? Or does this whole code need an overhaul?
First, pass the index:
for (var i = 0; i < results.products.length; i++) {
processResult(results.products[i], i);
}
Then check it:
function processResult(result, index) {
var newDiv = ...
//check if the index is a multiple of 6
if(index % 6 == 0){
//do something every six results
}
HTH,
-Ted
Since you want to append the new items to different DIVs, the processResults function might be the better place to do this:
function processResults(results) {
var i = 0,
length = results.length,
first = $("#galleryfirst"),
second = $("gallerysecond");
first.append('<div class="imageArtist">' + results[0].artist + '</div>');
for (i; i < 6 && i < length; i++) {
processResult(results[i], first);
}
if (length > 6) {
second.append('<div class="imageArtist">' + results[6].artist + '</div>');
for (i = 6; i < 12 && i < length; i++) {
processResult(results[i], second);
}
}
}
function processResult(product, containerId) {
var newDiv = "...";
// build the HTML for newDiv...
$(containerId).append(newDiv);
}

Dynamically add bootstrap rows using modulo

I a trying to dynamically add rows and populate them with 3 col-sm-4 using a modulo against the number of objects in a returned object from a function.
Code:
function formatSeriesCard(series) {
var card = "";
console.log(countProperties(series));
for (var i=0; i < countProperties(series); i++) {
if (i % 3 == 0 ) {
card += "<div class=\"row\">";
}
card += "<div class='col-sm-4' data-id="+i+">";
card += "<div class='action-box'>";
card += "<h4>" + '"' + series.name + '"' + "</h4>";
card += "<p>";
Instead I'm getting each row nested within the previous. Thinking I need to test for the first one and last one. Thanks.
Here is something like what you want
Bootply : http://www.bootply.com/2xnJBpyVsS
JS :
var wantedcol=14;
var mycol='<div class="col-xs-4">mycol</div>';
var startRowLabel="<div class='row'>";
var endRowLabel="</div>";
var start = "";
var end="";
var toAppend="";
for(var i=0; i<wantedcol; i++){
start="";
if(i%3==0 || i==0){
start=startRowLabel;
}
end="";
if(i!=0 && (i%3==2 || i==wantedcol-1)){
end=endRowLabel;
}
console.log(start+mycol+end);
toAppend+=start+mycol+end;
}
$('.container').append(toAppend);
HTML:
<div class="container"></div>
Comment :
You just have to take care about when you have to insert the div.row opening and closing tags

dynamically creating a table and adding cells to the table through a function with Javascript

I am wondering how to create a function with a for loop which creates new cells / rows for the other for loop to call upon. The function should return newRow which should be a specified amount of cells. The idea is the html code displays 3 images per row, but if there is just 2 images then it only needs 2 cells. That is the first if / else statement.
Here is the code so far..
var cells = document.getElementsByTagName('td');
var cell = '<td>' + cells[0].innerHTML + '</td>';
//console.log(cell);
document.getElementById('searchBtn').onclick = search;
//specified as 3 per row
var NUMPERROW = 3;
//gets number from form text input
var num = document.getElementById("searchtxt").value;
function search(){
//var num = 4;
console.log(num);
//loop once per row
var htmlStr = '';
for (var i = 0; i < num; i = i + NUMPERROW){
//htmlStr += '<tr>' + cell + cell + cell + '</tr>;
if (num - i >= NUMPERROW) {
//displays a new row of 3
htmlStr += newRow(NUMPERROW);
}else { //less then 3 to display
htmlStr += newRow(num - i);
}
}
document.getElementById('thumbnails').innerHTML = htmlStr;
}
/*
*Returns the html for a new row.
* numToAdd: the number of cells to add for this row.
*
*/
//this function i do not know how to write
function newRow(cellsToAdd){
/////?????????? should be a for loop return new Row for the for loop above
}
}
Here is a simple function if you don't want to pass the values you can leave content out.
function newRow(numberOfCells, content)
{
var result = '<tr>';
for(var i = 0; i < numberOfCells; i++)
result += '<td>' + content[i] + '</td>';
result += '</tr>';
return result;
}

Categories