I have on page div:
<div id="here_table"></div>
and in jquery:
for(i=0;i<3;i++){
$('#here_table').append( 'result' + i );
}
this generating for me:
<div id="here_table">
result1 result2 result3 etc
</div>
I would like receive this in table:
<div id="here_table">
<table>
<tr><td>result1</td></tr>
<tr><td>result2</td></tr>
<tr><td>result3</td></tr>
</table>
</div>
I doing:
$('#here_table').append( '<table>' );
for(i=0;i<3;i++){
$('#here_table').append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
$('#here_table').append( '</table>' );
but this generate for me:
<div id="here_table">
<table> </table> !!!!!!!!!!
<tr><td>result1</td></tr>
<tr><td>result2</td></tr>
<tr><td>result3</td></tr>
</div>
Why? how can i make this correctly?
LIVE: http://jsfiddle.net/n7cyE/
This line:
$('#here_table').append( '<tr><td>' + 'result' + i + '</td></tr>' );
Appends to the div#here_table not the new table.
There are several approaches:
/* Note that the whole content variable is just a string */
var content = "<table>"
for(i=0; i<3; i++){
content += '<tr><td>' + 'result ' + i + '</td></tr>';
}
content += "</table>"
$('#here_table').append(content);
But, with the above approach it is less manageable to add styles and do stuff dynamically with <table>.
But how about this one, it does what you expect nearly great:
var table = $('<table>').addClass('foo');
for(i=0; i<3; i++){
var row = $('<tr>').addClass('bar').text('result ' + i);
table.append(row);
}
$('#here_table').append(table);
Hope this would help.
You need to append the tr inside the table so I updated your selector inside your loop and removed the closing table because it is not necessary.
$('#here_table').append( '<table />' );
for(i=0;i<3;i++){
$('#here_table table').append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
The main problem was that you were appending the tr to the div here_table.
Edit: Here is a JavaScript version if performance is a concern. Using document fragment will not cause a reflow for every iteration of the loop
var doc = document;
var fragment = doc.createDocumentFragment();
for (i = 0; i < 3; i++) {
var tr = doc.createElement("tr");
var td = doc.createElement("td");
td.innerHTML = "content";
tr.appendChild(td);
//does not trigger reflow
fragment.appendChild(tr);
}
var table = doc.createElement("table");
table.appendChild(fragment);
doc.getElementById("here_table").appendChild(table);
When you use append, jQuery expects it to be well-formed HTML (plain text counts). append is not like doing +=.
You need to make the table first, then append it.
var $table = $('<table/>');
for(var i=0; i<3; i++){
$table.append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
$('#here_table').append($table);
Or do it this way to use ALL jQuery. The each can loop through any data be it DOM elements or an array/object.
var data = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'];
var numCols = 1;
$.each(data, function(i) {
if(!(i%numCols)) tRow = $('<tr>');
tCell = $('<td>').html(data[i]);
$('table').append(tRow.append(tCell));
});
http://jsfiddle.net/n7cyE/93/
To add multiple columns and rows, we can also do a string concatenation. Not the best way, but it sure works.
var resultstring='<table>';
for(var j=0;j<arr.length;j++){
//array arr contains the field names in this case
resultstring+= '<th>'+ arr[j] + '</th>';
}
$(resultset).each(function(i, result) {
// resultset is in json format
resultstring+='<tr>';
for(var j=0;j<arr.length;j++){
resultstring+='<td>'+ result[arr[j]]+ '</td>';
}
resultstring+='</tr>';
});
resultstring+='</table>';
$('#resultdisplay').html(resultstring);
This also allows you to add rows and columns to the table dynamically, without hardcoding the fieldnames.
Here is what you can do: http://jsfiddle.net/n7cyE/4/
$('#here_table').append('<table></table>');
var table = $('#here_table').children();
for(i=0;i<3;i++){
table.append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
Best regards!
Following is done for multiple file uploads using jquery:
File input button:
<div>
<input type="file" name="uploadFiles" id="uploadFiles" multiple="multiple" class="input-xlarge" onchange="getFileSizeandName(this);"/>
</div>
Displaying File name and File size in a table:
<div id="uploadMultipleFilediv">
<table id="uploadTable" class="table table-striped table-bordered table-condensed"></table></div>
Javascript for getting the file name and file size:
function getFileSizeandName(input)
{
var select = $('#uploadTable');
//select.empty();
var totalsizeOfUploadFiles = "";
for(var i =0; i<input.files.length; i++)
{
var filesizeInBytes = input.files[i].size; // file size in bytes
var filesizeInMB = (filesizeInBytes / (1024*1024)).toFixed(2); // convert the file size from bytes to mb
var filename = input.files[i].name;
select.append($('<tr><td>'+filename+'</td><td>'+filesizeInMB+'</td></tr>'));
totalsizeOfUploadFiles = totalsizeOfUploadFiles+filesizeInMB;
//alert("File name is : "+filename+" || size : "+filesizeInMB+" MB || size : "+filesizeInBytes+" Bytes");
}
}
Or static HTML without the loop for creating some links (or whatever). Place the <div id="menu"> on any page to reproduce the HTML.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML Masterpage</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function nav() {
var menuHTML= '<ul><li>link 1</li></ul><ul><li>link 2</li></ul>';
$('#menu').append(menuHTML);
}
</script>
<style type="text/css">
</style>
</head>
<body onload="nav()">
<div id="menu"></div>
</body>
</html>
I wrote rather good function that can generate vertical and horizontal tables:
function generateTable(rowsData, titles, type, _class) {
var $table = $("<table>").addClass(_class);
var $tbody = $("<tbody>").appendTo($table);
if (type == 2) {//vertical table
if (rowsData.length !== titles.length) {
console.error('rows and data rows count doesent match');
return false;
}
titles.forEach(function (title, index) {
var $tr = $("<tr>");
$("<th>").html(title).appendTo($tr);
var rows = rowsData[index];
rows.forEach(function (html) {
$("<td>").html(html).appendTo($tr);
});
$tr.appendTo($tbody);
});
} else if (type == 1) {//horsantal table
var valid = true;
rowsData.forEach(function (row) {
if (!row) {
valid = false;
return;
}
if (row.length !== titles.length) {
valid = false;
return;
}
});
if (!valid) {
console.error('rows and data rows count doesent match');
return false;
}
var $tr = $("<tr>");
titles.forEach(function (title, index) {
$("<th>").html(title).appendTo($tr);
});
$tr.appendTo($tbody);
rowsData.forEach(function (row, index) {
var $tr = $("<tr>");
row.forEach(function (html) {
$("<td>").html(html).appendTo($tr);
});
$tr.appendTo($tbody);
});
}
return $table;
}
usage example:
var title = [
'مساحت موجود',
'مساحت باقیمانده',
'مساحت در طرح'
];
var rows = [
[number_format(data.source.area,2)],
[number_format(data.intersection.area,2)],
[number_format(data.deference.area,2)]
];
var $ft = generateTable(rows, title, 2,"table table-striped table-hover table-bordered");
$ft.appendTo( GroupAnalyse.$results );
var title = [
'جهت',
'اندازه قبلی',
'اندازه فعلی',
'وضعیت',
'میزان عقب نشینی',
];
var rows = data.edgesData.map(function (r) {
return [
r.directionText,
r.lineLength,
r.newLineLength,
r.stateText,
r.lineLengthDifference
];
});
var $et = generateTable(rows, title, 1,"table table-striped table-hover table-bordered");
$et.appendTo( GroupAnalyse.$results );
$('<hr/>').appendTo( GroupAnalyse.$results );
example result:
A working example using the method mentioned above and using JSON to represent the data. This is used in my project of dealing with ajax calls fetching data from server.
http://jsfiddle.net/vinocui/22mX6/1/
In your html:
< table id='here_table' >< /table >
JS code:
function feed_table(tableobj){
// data is a JSON object with
//{'id': 'table id',
// 'header':[{'a': 'Asset Tpe', 'b' : 'Description', 'c' : 'Assets Value', 'd':'Action'}],
// 'data': [{'a': 'Non Real Estate', 'b' :'Credit card', 'c' :'$5000' , 'd': 'Edit/Delete' },... ]}
$('#' + tableobj.id).html( '' );
$.each([tableobj.header, tableobj.data], function(_index, _obj){
$.each(_obj, function(index, row){
var line = "";
$.each(row, function(key, value){
if(0 === _index){
line += '<th>' + value + '</th>';
}else{
line += '<td>' + value + '</td>';
}
});
line = '<tr>' + line + '</tr>';
$('#' + tableobj.id).append(line);
});
});
}
// testing
$(function(){
var t = {
'id': 'here_table',
'header':[{'a': 'Asset Tpe', 'b' : 'Description', 'c' : 'Assets Value', 'd':'Action'}],
'data': [{'a': 'Non Real Estate', 'b' :'Credit card', 'c' :'$5000' , 'd': 'Edit/Delete' },
{'a': 'Real Estate', 'b' :'Property', 'c' :'$500000' , 'd': 'Edit/Delete' }
]};
feed_table(t);
});
As for me, this approach is prettier:
String.prototype.embraceWith = function(tag) {
return "<" + tag + ">" + this + "</" + tag + ">";
};
var results = [
{type:"Fiat", model:500, color:"white"},
{type:"Mercedes", model: "Benz", color:"black"},
{type:"BMV", model: "X6", color:"black"}
];
var tableHeader = ("Type".embraceWith("th") + "Model".embraceWith("th") + "Color".embraceWith("th")).embraceWith("tr");
var tableBody = results.map(function(item) {
return (item.type.embraceWith("td") + item.model.toString().embraceWith("td") + item.color.embraceWith("td")).embraceWith("tr")
}).join("");
var table = (tableHeader + tableBody).embraceWith("table");
$("#result-holder").append(table);
i prefer the most readable and extensible way using jquery.
Also, you can build fully dynamic content on the fly.
Since jquery version 1.4 you can pass attributes to elements which is, imho, a killer feature.
Also the code can be kept cleaner.
$(function(){
var tablerows = new Array();
$.each(['result1', 'result2', 'result3'], function( index, value ) {
tablerows.push('<tr><td>' + value + '</td></tr>');
});
var table = $('<table/>', {
html: tablerows
});
var div = $('<div/>', {
id: 'here_table',
html: table
});
$('body').append(div);
});
Addon: passing more than one "html" tag you've to use array notation like:
e.g.
var div = $('<div/>', {
id: 'here_table',
html: [ div1, div2, table ]
});
best Rgds.
Franz
<table id="game_table" border="1">
and Jquery
var i;
for (i = 0; ii < 10; i++)
{
var tr = $("<tr></tr>")
var ii;
for (ii = 0; ii < 10; ii++)
{
tr.append(`<th>Firstname</th>`)
}
$('#game_table').append(tr)
}
this is most better
html
<div id="here_table"> </div>
jQuery
$('#here_table').append( '<table>' );
for(i=0;i<3;i++)
{
$('#here_table').append( '<tr>' + 'result' + i + '</tr>' );
for(ii=0;ii<3;ii++)
{
$('#here_table').append( '<td>' + 'result' + i + '</tr>' );
}
}
$('#here_table').append( '</table>' );
It is important to note that you could use Emmet to achieve the same result. First, check what Emmet can do for you at https://emmet.io/
In a nutshell, with Emmet, you can expand a string into a complexe HTML markup as shown in the examples below:
Example #1
ul>li*5
... will produce
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
Example #2
div#header+div.page+div#footer.class1.class2.class3
... will produce
<div id="header"></div>
<div class="page"></div>
<div id="footer" class="class1 class2 class3"></div>
And list goes on. There are more examples at https://docs.emmet.io/abbreviations/syntax/
And there is a library for doing that using jQuery. It's called Emmet.js and available at https://github.com/christiansandor/Emmet.js
Here the below code helps to generate responsive html table
#javascript
(function($){
var data = [{
"head 1": "row1 col 1",
"head 2": "row1 col 2",
"head 3": "row1 col 3"
}, {
"head 1": "row2 col 1",
"head 2": "row2 col 2",
"head 3": "row2 col 3"
}, {
"head 1": "row3 col 1",
"head 2": "row3 col 2",
"head 3": "row3 col 3"
}];
for (var i = 0; i < data.length; i++) {
var accordianhtml = "<button class='accordion'>" + data[i][small_screen_heading] + "<span class='arrow rarrow'>→</span><span class='arrow darrow'>↓</span></button><div class='panel'><p><table class='accordian_table'>";
var table_row = null;
var table_header = null;
for (var key in data[i]) {
accordianhtml = accordianhtml + "<tr><th>" + key + "</th><td>" + data[i][key] + "</td></tr>";
if (i === 0 && true) {
table_header = table_header + "<th>" + key + "</th>";
}
table_row = table_row + "<td>" + data[i][key] + "</td>"
}
if (i === 0 && true) {
table_header = "<tr>" + table_header + "</tr>";
$(".mv_table #simple_table").append(table_header);
}
table_row = "<tr>" + table_row + "</tr>";
$(".mv_table #simple_table").append(table_row);
accordianhtml = accordianhtml + "</table></p></div>";
$(".mv_table .accordian_content").append(accordianhtml);
}
}(jquery)
Here we can see the demo responsive html table generator
let html = '';
html += '<table class="tblWay" border="0" cellpadding="5" cellspacing="0" width="100%">';
html += '<tbody>';
html += '<tr style="background-color:#EEEFF0">';
html += '<td width="80"> </td>';
html += '<td><b>Shipping Method</b></td>';
html += '<td><b>Shipping Cost</b></td>';
html += '<td><b>Transit Time</b></td>';
html += '</tr>';
html += '</tbody>';
html += '</table>';
$('.product-shipping-more').append(html);
Related
I cant find my fail in the code why the secound for loop doesnt work. Please help me. thx
i tried to modify the for code. i tried to look if it works without the secound loop and it does. any idea?
//--js file with the object array which is loaded in the 2nd file--
let inhaltsverzeichnis_beispiele = [
{ blatt:'1'
,name: ['Übungszettel 1 [2013]', 'Übungszettel 1 [2014]', 'Übungszettel 1 [2018]']
,a_href: ['Übungsbeispiele_1_2013','Übungsbeispiele_1_2014','Übungsbeispiele_1_2018']
,fach: ['Physik Integral- und Differentionrechnungen','Physik Integral- und Differentionrechnungen','Informatik AnalysisT1']
},
]
//----2nd file code segment
document.write('<button class="buttn" onclick="myFunction(\'index\')" style="color:red;">Inhaltsverzeichnis</button><div id="index" style="display:none;"><ul style="list-style: none;">');
for (NR_i = 0; NR_i < inhaltsverzeichnis_beispiele.length; NR_i++) {
document.write(
'<li>'
+ '<table>'
+ '<tr>'
+ '<td style="width:30px">'
+ inhaltsverzeichnis_beispiele[NR_i].blatt
+ '</td>'
);
//---- That loop doesnt work =/
for (NR_i2 = 0; NR_i2 < inhaltsverzeichnis_beispiele[Nr_i].name[NR_i2].length; NR_i2++) {
document.write(
+ '<td>'
+ '<a href="#'
+ inhaltsverzeichnis_beispiele[NR_i].a_href[NR_i2]
+ '" >'
+ inhaltsverzeichnis_beispiele[NR_i].name[NR_i2]
+ '</a>'
+ '</td>'
)
}
//----- That loop doesnt work =/ End
document.write(
+ '</tr>'
+ '</table>'
+'</li>'
);
};
document.write('</ul></div>');
//----2nd file code segment End
You could take some array methods for iterating the data and build new elements and add them to the body (or any other element of the web page).
var inhaltsverzeichnis_beispiele = [{ blatt: '1', name: ['Übungszettel 1 [2013]', 'Übungszettel 1 [2014]', 'Übungszettel 1 [2018]'], a_href: ['Übungsbeispiele_1_2013', 'Übungsbeispiele_1_2014', 'Übungsbeispiele_1_2018'], fach: ['Physik Integral- und Differentionrechnungen', 'Physik Integral- und Differentionrechnungen', 'Informatik AnalysisT1'] }],
ul = document.createElement('ul');
inhaltsverzeichnis_beispiele.forEach(({ blatt, name, a_href }) => {
var li = document.createElement('li'),
table = document.createElement('table'),
tr = document.createElement('tr'),
td = document.createElement('td');
td.style = 'width:30px;';
td.appendChild(document.createTextNode(blatt));
tr.appendChild(td);
name.forEach((value, i) => {
var td = document.createElement('td'),
a = document.createElement('a');
a.href = a_href[i];
a.appendChild(document.createTextNode(value));
td.appendChild(a);
tr.appendChild(td);
});
table.appendChild(tr);
li.appendChild(table);
ul.appendChild(li);
});
document.body.appendChild(ul);
I recommmend that you use es6 features and redo your code into something like this.
This uses a combination of template literals, Array#map, and Array#join
//--js file with the object array which is loaded in the 2nd file--
const inhaltsverzeichnis_beispiele = [{
blatt: '1',
name: ['Übungszettel 1 [2013]', 'Übungszettel 1 [2014]', 'Übungszettel 1 [2018]'],
a_href: ['Übungsbeispiele_1_2013', 'Übungsbeispiele_1_2014', 'Übungsbeispiele_1_2018'],
fach: ['Physik Integral- und Differentionrechnungen', 'Physik Integral- und Differentionrechnungen', 'Informatik AnalysisT1']
}];
const container = document.getElementById("container");
const buttonContainer = document.getElementById("button-container");
buttonContainer.innerHTML = `<button class="buttn" onclick="myFunction('index')" style="color:red;">Inhaltsverzeichnis</button>`
function generateTable(data){
const res = [`<td style="width:30px">${data.blatt}</td>`];
for(let i = 0; i < data.name.length; i++){
const name = data.name[i];
const href = data.a_href[i];
res.push(`<td>${name}</td>`);
}
return `<table><tr>${res.join("")}</tr></table>`
}
function generateList(data){
const res = data.map(item=>{
const table = generateTable(item);
return `<li>${table}</li>`;
}).join("");
return `<ul>${res}</ul>`
}
container.innerHTML = generateList(inhaltsverzeichnis_beispiele);
<div id="button-container">
</div>
<div id="container">
</div>
My question is: how do I get the value of the clicked row and column?
The code I have is this:
JS:
$.ajax({
type: 'POST',
url: url,
data: json,
success: function(data) {
var response_array = JSON.parse(data);
var columns = ['id', 'name', 'email', 'telephone', 'website', 'city'];
var table_html = ' <tr>\n' +
'<th id="id">Id</th>\n' +
'<th id="name">Bedrijfnaam</th>\n' +
'<th id="email">E-mail</th>\n' +
'<th id="telephone">Telefoon</th>\n' +
'<th id="website">Website</th>\n' +
'<th id="city">Plaats</th>\n' +
'</tr>';
for (var i = 0; i < response_array.length; i++) {
//create html table row
table_html += '<tr>';
for (var j = 0; j < columns.length; j++) {
//create html table cell, add class to cells to identify columns
table_html += '<td class="' + columns[j] + '" >' + response_array[i][columns[j]] + '</td>'
}
table_html += '</tr>'
};
$("#posts").append(table_html);
},
error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
});
Here is the HTML:
<div class="tabel">
<table id="posts">
</table>
</div>
I have tried the following:
$('#posts').click(function(){
console.log("clicked");
var id = $("tr").find(".id").html();
console.log(id);
});
Sadly this will only give me the id of the first row, no matter where I click.
Any help is appreciated!
Ramon
The below approach should be able to find the ID
$('#post').on('click', function(e){
var id = $(e.target).closest('tr').find(".id").html();
console.log(id)
})
HTML content of clicked row
$('#posts tr').click(function(){
$(this).html();
});
text from clicked td
$('#posts tr td').click(function(){
$(this).text();
});
If you are using ajax and you are redrawing elements, you will not catch em via click function. You will need to add on function:
$(document).on('click','#posts tr td','function(){
$(this).text();
});
You may try to use AddEventListener for your table, it will work for sure.
Like this:
let posts = document.getlementById('posts');
posts.addEventListener('click',(e) => {
// anything you need here, for example:
console.log(e.target);
e.preventDefault();
});
As well - it will be fine not to use same IDs for elements in a grid (like id="id" which you have), it should be different.
I am not very familiar with JavaScript and AJAX.
I am developing a webpage that displays information return by a §.getJSON / JQuery request. But this function only works, when I start debugging. I know that the debugger corrects the timing and scope from other post on this topic. But I cannot find my mistake. I do not realy need a long explaination, because as I said before I am not very familiar with JavaScript/AJAX. This is the script-part in the page (you can ignore the addDropDown() and the departmentSelected() functions(as far as i know)):
<script type="text/javascript">
var isSelected = [];
$(addDropDown);
function addDropDown(){
$.getJSON("./api/persence/departments/all", function(data, status){
if(status !== "success"){
alert(status);
}else{
var dropdownHead = "<button class='btn btn-primary dropdown-toggle' type='button' data-toggle='dropdown'>Abteilungen<span class='caret'><\/span><\/button>";
var dropdownBody = "<ul class='dropdown-menu'>";
var i;
for(i = 0; i < data.length; i++){
dropdownBody = dropdownBody + "<li><a href='javascript:departmentSelected(" + i + "," + data[i].departmentId + ");'>";
dropdownBody = dropdownBody + data[i].departmentName;
dropdownBody = dropdownBody + " - ";
dropdownBody = dropdownBody + data[i].departmentCity;
dropdownBody = dropdownBody + "<\/a><\/li>";
}
dropdownBody = dropdownBody + "<\/ul>";
dropdownHead = dropdownHead + dropdownBody;
$("#dropdown-list").append(dropdownHead);
isSelected.length = i + 1;
}
});
}
function departmentSelected(position, value){
if((isSelected[position] !== value)){
isSelected[position] = value;
}else{
isSelected[position] = "false";
}
loadTable();
}
function loadTable(){
var tHead = "<br><div class='table-responsive'><table class='table'><thead><tr><th>#</th><th>Name<\/th><th>Beruf<\/th><th>Anwesend<\/th><th>Arbeitsplatz<\/th><\/tr><\/thead>";
var tBody = "<tbody>";
for(var i = 0; i < isSelected.length; i++){
var counter = 0;
if(isSelected[i] !== "false"){
$.getJSON("./api/persence/departments/" + isSelected[i]).then(function(result, status){
if(status !== "success"){
alert(status);
}else{
for(var i = 0; i < result.length; i++) {
var employee = result[i];
tBody = tBody + "<tr> <td>" + counter + "<\/td>";
tBody = tBody + "<td>" + employee.academicTitle + " " + employee.lastName + " " + employee.firstName + "<\/td>";
tBody = tBody + "<td>" + employee.job + "<\/td>";
tBody = tBody + "<td>";
if(employee.persenceStatus === "Y"){
tBody = tBody + employee.persenceSince;
}else{
// if(employee.absenceReason !== null){
tBody = tBody + employee.absenceReason;
// }
//else{
// tBody = tBody + " ";
//}
}
tBody = tBody + "<\/td>";
tBody = tBody + "<td>" + employee.workplace + "<\/td>";
tBody = tBody + "<\/tr>";
counter++;
}
}
});
}
}
tBody = tBody + "<\/tbody> <\/table> <\/div>";
tHead = tHead + tBody;
document.getElementById("outputTable").innerHTML = tHead;
}
My Problem: I can not find what I have done wrong in this scriptpart, because the debugger (firebug) is able to optimize the code while debugging so it works perfectly fine. But if I am not in debug-mode, only the "head-line" of the table is displayed (the information is missing).
Thanks for your help.
This problem is about the finding element in DOM. Sometimes Js faster than DOM and Js can't find specific element in html DOM. You need to define js code in onLoad.
$(function() {
$(addDropDown);
});
OR
$(document).ready(function(){
$(addDropDown);
});
Inportant Info: If you include jQuery don't use JS specific functions. Sometimes it crash with jquery. Just use jQuery functions.
Example:
not good : document.getElementById("outputTable")
good : '$.("#outputTable")'
Ok, I solved the problem myself: I had to put the following part into the function called by the jQuery request (function(result, status).....)
tBody = tBody + "</tbody> </table> </div>";
tHead = tHead + tBody;
document.getElementById("outputTable").innerHTML = tHead;
Can you please tell me how to make list in jQuery mobile? I am trying to make this type list as given in fiddle on pop up screen dynamically .
Here is the fiddle
In this fiddle I make two rows.In first row there is only p tag. But in second row there is nested collapsible rows. I need to make same thing in pop up screen. I am able to make first row. But In my second row contend is null why? Can you suggest where I am wrong?
fiddle
$(function () {
$('#test').click(function(){
alert('d');
createCommandPopUpTabs();
$("#tabbedPopup").popup("open");
});
});
var tabsHeader = [ "InputParameter", "basic"];
var tabsHeader_basic = [ "XYZ", "Third Level",
];
function createCommandPopUpTabs(){
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("'+
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").append(button);
$("#commandInfoheader").html(header);
for ( var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>InputParameter</h3></div>";
var content ;
if(tabsHeader[i]=="InputParameter"){
content = "<p>yes</p>";
}else if(tabsHeader[i]=="basic"){
for ( var i = 0; i < tabsHeader_basic.length; i++) {
headerId = tabsHeader_basic[i] + "_tab" + commmand;
header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>basic</h3></div>";
content += getcontend(tabsHeader_basic[i]);
}
}
$("#tabbedSet").append(header);
$("#tabbedSet").find("#" + headerId).append(content);
$("#tabbedSet").collapsibleset("refresh");
}
}
function getcontend(name){
if(name=="Third Level"){
return"<p>Third Level></p>";
} if(name=="XYZ"){
return"<p> second Level></p>";
}
}
There are errors in your code and logic. I will only go over a couple of them to hopefully get you on the right path:
In tabsHeader_basic array the Third Level has a space in it which you later use as an ID which makes it an invalid ID because you cannot have spaces in an ID.
From the HTML 5 Draft:
The value must not contain any space characters.
Also, the "basic" collapsible div needs to exist before you start adding the nested collapsible div.
So this line needs to come out of the for loop
header = "<div data-role='collapsible' data-collapsed='false' id='"+ headerId + "'><h3>basic</h3></div>";
Go through the JSFiddle and compare your code agaisnt my changes.
Hopefully that helps! Let me know if you have any other questions.
I have updated createCommandPopUpTabs() function.
Also removed space in Third Level on var tabsHeader_basic = ["XYZ", "ThirdLevel"];
Check the Updated Fiddle
function createCommandPopUpTabs() {
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("' +
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").html(button);
$("#commandInfoheader").html(header);
$("#tabbedSet").html('');
for (var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='true' id='" + headerId + "'><h3>" + tabsHeader[i] + "</h3></div>";
$("#tabbedSet").append(header);
var content;
if (tabsHeader[i] == "InputParameter") {
content = "<p>yes</p>";
$("#tabbedSet").find("#" + headerId).append(content);
} else if (tabsHeader[i] == "basic") {
for (var j = 0; j < tabsHeader_basic.length; j++) {
var headerId1 = tabsHeader_basic[j] + "_tab" + commmand;
var header1 = "<div data-role='collapsible' data-collapsed='true' id='" + headerId1 + "'><h3>" + tabsHeader_basic[j] + "</h3></div>";
var content1 = getcontend(tabsHeader_basic[j]);
$("#tabbedSet").find("#" + headerId).append(header1);
$("#tabbedSet").find("#" + headerId1).append(content1);
}
}
$("#tabbedSet").collapsibleset("refresh");
}
}
Basically, I want the user the just change the 'height' variable to how ever many rows he wants, and then store the words which each td in the row should contain, and the code should then generate the table.
My html is just this:
<table id="newTable">
</table>
This is my Javascript:
<script type="text/javascript">
var height = 2; // user in this case would want 3 rows (height + 1)
var rowNumber = 0;
var height0 = ['HeadingOne', 'HeadingTwo']; // the words in each td in the first row
var height1 = ['firstTd of row', 'secondTd of row']; // the words in each td in the second row
var height2 = ['firstTd of other row', 'secondTd of other row']; // the words in each td in the third row
$(document).ready( function() {
createTr();
});
function createTr () {
for (var h=0; h<height + 1; h++) { // loop through 3 times, in this case (which h<3)
var theTr = "<tr id='rowNumber" + rowNumber + "'>"; // <tr id='rowNumber0'>
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
for (var i=0; i<window['height' + rowNumber].length; i++) {
if (i == window['height' + rowNumber].length-1) { // if i==2, then that means it is the last td in the tr, so have a </tr> at the end of it
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td></tr>";
$('#rowNumber' + rowNumber).append(theTr); // append to the end of the Tr
} else {
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td>";
$('#rowNumber' + rowNumber).append(theTr);
}
}
rowNumber += 1;
}
}
</script>
I did 'alert(theTr);' and 'alert(theTd);' and they looked correct. How come this code doesn't generate any table?
You should change the line
$('#rowNumber' + rowNumber).append(theTr);
into
$('#rowNumber' + rowNumber).append(theTd);
You are adding the Tr-Code again in the inner loop, but you actually wanted to add the Td-Code.
All that window["height"+rowNumber] stuff is a poor way to do it. Use an array, and pass it as a parameter to the function so you don't use global variables. And use jQuery DOM creation functions instead of appending strings.
<script type="text/javascript">
var heights = [['HeadingOne', 'HeadingTwo'], // the words in each td in the first row
['firstTd of row', 'secondTd of row'], // the words in each td in the second row
['firstTd of other row', 'secondTd of other row'] // the words in each td in the third row
];
$(document).ready( function() {
createTr(heights);
});
function createTr (heights) {
for (var h=0; h<heights.length; h++) { // loop through 3 times, in this case (which h<3)
var theTr = $("<tr>", { id: "rowNumber" + h});
for (var i=0; i<heights[h].length; i++) {
theTr.append($("<td>", { "class": "row"+h + " column"+i,
text: heights[h][i]
}));
}
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
}
}
</script>
JSFIDDLE