dynamically generted html table cannot get selected td value - javascript

I have looked at MANY google and stackoverflow examples
I did create a fiddle to demonstrate my problem.
Problem statement. "I want to get the name of the person in the first column upon clicking on their name." I have it so on rollover the class for each row highlights in yellow and I CAN get Jquery to do a click event and so that works, but when I do this code it spits out all of the text values for every row in that column
$(document).on('click', '.nameField', function () {
//console.log('t');
var x = $(".nameField").text();
//var x = $(this).parent(".nameField").text();
console.log(x);
});
http://jsfiddle.net/bthorn/7ck1m7q1/2/
More Info.
Click on the button "Fill DIV with Dynamic Table"
Also at the top , notice a STATIC one that on there at the top works to get the name no problem, well there is only one row though
UPDATE I NEED ALIAS on that row I created a new class on the td in the alias column, How can I get at that?
http://jsfiddle.net/bthorn/7ck1m7q1/2/

You can try
var x = $(this).text();
And to get the alias:
var x = $(this).siblings('.alias').text();

$(".nameField") will return you nodelist of elements. Use this. Fiddle
$('.person').on('click', function() {
var x = $(".person").text();
console.log(x);
});
$(document).on('click', '.nameField', function() {
var x = $(this).text();
console.log(x);
});
$('#fillTable').click(function() {
var data = [{
'Email': 't.Miller#companyemail.com',
'LastFirst': 'abcsaker,b',
'FIRST_NAME': 'b',
'INITIALS': 'W ',
'LAST_NAME': 'abcsaker',
'ALIAS_NAME': 'BWabcSAK',
'OFFICE': 'sdfdf ',
'TITLE': 'rrr EQUIPMENT 3',
'DEPARTMENT': 'Construction East',
'EMPLOYEE_NUMBER': '444 '
}, {
'Email': 'abcter.plethcer#companyemail.com',
'LastFirst': 'stillman,abcter',
'FIRST_NAME': 'abcter',
'INITIALS': 'A ',
'LAST_NAME': 'Streeper',
'ALIAS_NAME': 'HASTREEP',
'OFFICE': 'adfafd ',
'TITLE': 'TRADES HELPER 2ND YEAR',
'DEPARTMENT': 'ee Locating - West',
'EMPLOYEE_NUMBER': '6666 '
}, {
'Email': 'brad.abckele#companyemail.com',
'LastFirst': 'abckele,brad',
'FIRST_NAME': 'brad',
'INITIALS': 'J ',
'LAST_NAME': 'abckele',
'ALIAS_NAME': 'CJabcKEL',
'OFFICE': 'adffg ',
'TITLE': 'DESIGNER d SR - (asfe)',
'DEPARTMENT': 'afe Design A',
'EMPLOYEE_NUMBER': '999 '
}];
writeRegister(data);
});
function writeRegister(allData) {
//console.log(allData);
//$('#matchText').text(allData.length + ' matches.');
var strResult = "<table id='headerTable' class='table'><thead id='headers'><th>Name</th><th>Office</th><th>Title</th><th>Department</th><th>Alias</th>";
$.each(allData, function(index, issues) {
strResult += "<tr><td class='nameField'> <a href='#'>" + issues.LAST_NAME + " " + issues.FIRST_NAME + " " + issues.INITIALS + "</a></td><td>" + issues.OFFICE + "</td><td>" + issues.TITLE + "</td>";
strResult += "<td>" + issues.DEPARTMENT + "</td><td>" + issues.ALIAS_NAME + "</td>";
strResult += "</tr>";
});
strResult += "</table>";
$("#divEmpResult").html(strResult);
}
td.person {
color: red;
}
.person:hover {
color: red !important;
background-color: yellow;
}
.nameField:hover {
color: red !important;
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="person"><a href='#'>Miller Bob T</a>
</td>
</tr>
</table>
<!-- dynamic table generation is the problem -->Fill the DIV with dynamically created TABLE
<input type="button" id="fillTable" value="Fill DIV with Dynamic Table">
<div id="divEmpResult" style="margin-left: 15px"></div>

$(".nameField") will get all the td's with the class "nameField", instead use "this".
$(document).on('click', '.nameField', function () {
//console.log('t');
var x = $(this).text();
//var x = $(this).parent(".nameField").text();
console.log(x);
});

Try this instead, get the tr, and then find the .nameField associated with it
$(document).on('click', 'tr', function () {
//console.log('t');
var that = $(this);
var x = that.find($(".nameField")).text();
//var x = $(this).parent(".nameField").text();
console.log(x);
});

Most of the jquery functions doenst recognize dynamically generated elements.
To do that you need to use the function .live();
$(document).live('click', '.nameField', function () {
//console.log('t');
var x = $(".nameField").text();
//var x = $(this).parent(".nameField").text();
console.log(x);
});

Related

Javascript - Getting removed item name from table?

So I have an table. By click of a button, information will be added there, so each item has also X button, which removes them from the list. I've been trying to do that, if you click that X button, then it will output to console the item name which you deleted. How could I do that?
Here's the function
function sitaSeen(img, name, condition, price) {
$('tbody').append("<tr id='itemCart'><td><img src=" + img + "></td><td>" + name + "</td><td>" + condition + "</td><td>$" + price + "</td><td><span>X</span></td></tr>");
Which is called, when item has to be added.
Here's the X button code
$(document).ready(function() {
$('.sweet-container').on('click', 'tr span', function(){
var removedname = $(this).closest('tr').ignore('span').text();
console.log(removedname);
$(this).closest('tr').remove();
});
});
There's also kind of my try, but ofc it wont work.
There is no ignore() method in jQuery so it will throws error in console. So either clone the tr and remove span from cloned object and then get text or get all td which is not contains span and get text.
$(document).ready(function() {
$('.sweet-container').on('click', 'tr span', function(){
var removedname = $(this).closest('tr').clone().remove('span').text();
// or
// var removedname = $(this).closest('tr').find('td:not(:has(span))').text();
console.log(removedname);
$(this).closest('tr').remove();
});
});
UPDATE : Since you just want the second column you can simply use :nth-child or :eq() selector(or eq()).
$(document).ready(function() {
$('.sweet-container').on('click', 'tr span', function(){
var removedname = $(this).closest('tr').find('td:nth-child(2)').text();
// or
// $(this).closest('tr').find('td:eq(1)').text();
// or
// $(this).closest('tr').children().eq(1).text();
console.log(removedname);
$(this).closest('tr').remove();
});
});
I think it might be better to use:
```
// better way to get to the tr element
var trElem = $(this).parentNode.parentNode;
```
The parentNode attribute is a better way to access the parent of an element.
The item name is the second td so you can use:
var removedname = $(this).closest('tr').find('td:eq(1)').text();
Because the ID have to be unique I added a new parameter to your function.
function sitaSeen(seq, img, name, condition, price) {
$('tbody').append("<tr id='itemCart" + seq + "'>" +
"<td><img src=" + img + "></td>" +
"<td>" + name + seq + "</td>" +
"<td>" + condition + "</td>" +
"<td>$" + price + "</td>" +
"<td><span>X</span></td>" +
"</tr>");
}
$(function () {
$('#addRow').on('click', function(e) {
var seq = +$(this).attr('data-seq');
$(this).attr('data-seq', seq + 1);
sitaSeen(seq, 'img', 'name', 'condition', 'price');
});
$('.sweet-container').on('click', 'tr span', function(){
var removedname = $(this).closest('tr').find('td:eq(1)').text();
console.log(removedname);
$(this).closest('tr').remove();
});
});
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<div class="sweet-container">
<button id="addRow" data-seq="1">Add Row</button>
<table>
<tbody>
</tbody>
</table>
</div>

HTML table display JQuery checkbox off-by-one and not preserving data

I have some JavaScript code that should display a matrix of checkboxes. I want to list the column titles across the top, and then put rows where there is a column of checkboxes under each header, plus a left-hand column with row names under a blank header box. I'm going for the look on this page:
http://codepen.io/marclundgren/pen/hgelI
I wrote a Fiddle that almost works:
https://jsfiddle.net/bv01xvdf/
The first problem is that my table displays the checkboxes on a separate line from the cell with the row name. I checked my HTML, and it seems correct, but I'm wondering if I'm missing a <tr> or a </tr> somewhere. I add the row name cell like this (see the Fiddle for complete code):
var chugNames = ["Ropes", "Cooking", "Outdoor Cooking"];
for (x = 0; x < chugNames.length; x++) {
// Add a row for each name.
target.append("<tr><td>" + chugNames[x] + "</td>");
for (y = 0; y < chugNames.length; y++) {
target.append("<td><input type=\"checkbox\" />");
checkbox = $('</input>', {
'type': 'checkbox',
'data-x': chugNames[x],
'data-y': chugNames[y],
});
target.append(checkbox);
target.append("</td>");
}
target.append("</tr>");
}
The other problem is that data-x and data-y return "undefined" when I access them later in my "on" method:
target.on('change', 'input:checkbox', function() {
var $this = $(this),
x = $this.data('x'),
y = $this.data('y'),
checked = $this.prop('checked');
alert('checkbox changed chug intersection (' + x + ', ' + y + '): ' + checked);
});
When I check a box, I get "checkbox changed chug intersection (undefined, undefined): true". It should print something like (Ropes, Cooking), depending on which box was checked.
Any help would be greatly appreciated.
When you append with jQuery the tag is automatically closed.
check the jsfiddle
Try this:
$(function() {
var target = $('#checkboxes');
var chugNames = ["Ropes", "Cooking", "Outdoor Cooking"];
var i, x, y, checkbox, html;
html = "<table class=\"responsive-table-input-matrix\"><thead><tr><th></th>";
// Table column headers
for (i = 0; i < chugNames.length; i++) {
html += "<th>" + chugNames[i] + "</th>";
}
html += "</tr></thead><tbody>";
for (x = 0; x < chugNames.length; x++) {
// Add a row for each chug.
html += "<tr><td>" + chugNames[x] + "</td>";
for (y = 0; y < chugNames.length; y++) {
html += "<td>";
checkbox = '<input type=checkbox ';
checkbox += ' data-x=' + chugNames[x]
checkbox += ' data-y=' + chugNames[y]
checkbox += '/>'
html += checkbox;
html += "</td>";
}
html += "</tr>";
}
html += "</tbody></table>";
target.append(html).width(function() {
return $(this).find("input:checkbox").outerWidth() * chugNames.length
});
target.on('change', 'input:checkbox', function() {
var $this = $(this),
x = $this.data('x'),
y = $this.data('y'),
checked = $this.prop('checked');
alert('checkbox changed chug intersection (' + x + ', ' + y + '): ' + checked);
});
});
I fixed your jsfiddle here.
For the record, you had a few problems, an extra <th></th> in the opening string, an extra output of ChugName[x] and you didn't use the attr() jQuery function to get the data attributes properly.

How to access via jquery to select controls created dynamically

I have created dynamically some select controls(a.k.a. groupbox) but every time that I try to access to one of them if get the followig error:
Uncaught TypeError: undefined is not a function
Here is the code:
var method =$("#slt" + (parseInt(buttonElementId + 1))).children("option").is("selected").text();
Where parseInt(buttonElementId + 1 is always a number so the error is not there
<html>
<head lang="en">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
<style>
body { padding-top:80px; }
html, body, #wrapper
{
width: 100%;
height: 100%;
}
</style>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div class="container">
<div id="information"></div>
<div id="tableInformation"></div>
<div id="goBack"></div>
<br/>
<div id="inputDiv"></div>
<br/>
<br/>
<div id="UserGuide"></div>
</div>
<script src="js/jquery-1.11.js"> </script>
<script>
var apiUrl = 'http://localhost/devices';
$( document ).ready(function() {
// Handler for .ready() called.
jsonGETRequest(apiUrl, jsonExampleData);
});
$(document).on('click', ':button' , function() {
// reference clicked button via: $(this)
$("#UserGuide").empty();
var buttonElementId = $(this).attr('id');
if(buttonElementId.indexOf("btnShowFunc") > -1) {
buttonElementId = buttonElementId.replace("btnShowFunc","");
deviceUID = document.getElementById("mytable").rows[(parseInt(buttonElementId) + 1)].cells[1].innerHTML;
goBack = "firstAPIRequest";
$("#tableInformation tbody").remove();
jsonGETRequest(apiUrl + "/" + deviceUID + "/functions", jsonExampleDataFunctions);
} else if(buttonElementId.indexOf("btnGoBack") > -1 ) {
switch (goBack) {
case "firstAPIRequest":
goBack = "";
$("#tableInformation tbody").remove();
jsonGETRequest(apiUrl, jsonExampleData);
removeGoBackInputDiv();
break;
case "secondAPIRequest":
goBack = "firstAPIRequest";
$("#tableInformation tbody").remove();
jsonGETRequest(apiUrl + "/" + deviceUID + "/functions", jsonExampleDataFunctions);
removeGoBackInputDiv();
break;
}
}else if(buttonElementId.indexOf("btnRunFunc") > -1) {
goBack = "secondAPIRequest";
buttonElementId = buttonElementId.replace("btnRunFunc","");
var functionUID = document.getElementById("mytable").rows[(parseInt(buttonElementId) +1)].cells[2].innerHTML;
var method =$("#slt" + (parseInt(buttonElementId + 1))).children("option").is("selected").text();
$("#tableInformation tbody").remove();
$("#inputDiv").empty();
// /jsonPOST(apiUrl '/functions/' + functionUID )
}
});
function loadDataIntoDeviceGrid(jsonData) {
//$("#tableInformation").addClass("table table-responsive table-bordered");
var tbl=$("<table/>").attr("id","mytable");
$("#tableInformation").append(tbl);
$("#mytable").append("<tr>" + "<th>dal.device.status</th>" + "<th>dal.device.UID</th>"
+ "<th>dal.device.driver</th>" + "<th>service.id</th>" +"<th></th>" + "</tr>");
for(var i=0;i<jsonData.length;i++)
{
var tr = "<tr>";
var td1 = "<td>"+jsonData[i]["dal.device.status"]+"</td>";
var td2 = "<td>"+jsonData[i]["dal.device.UID"]+"</td>";
var td3 = "<td>"+jsonData[i]["dal.device.driver"]+"</td>";
var td4 = "<td>"+jsonData[i]["service.id"]+"</td>";
//#Deprecated var dataList = fillSelectControl(jsonData[i]["objectClass"]); #Deprecated
var btn = "<td>" + "<button id='btnShowFunc"+ i + "' class='btn btn-success btn-lg'>See function</button>" + "</td></tr>";
$("#mytable").append(tr + td1 + td2 + td3 + td4 + btn );
}
$("#mytable").addClass("table table-responsive table-bordered");
}
function loadInformationDeviceGrid() {
$("#UserGuide").addClass("alert alert-info");
$("#UserGuide").html("<h3>Getting devices list:</h3><br/> "+
"Using this request, you can retrieve a list of all the available devices."+
"For every device, among other info, there is the indication of the device unique ID, which" +
"can be used to directly access to the device and the indication of the device driver (ZigBee, Bluetooth, etc.).<br/>If you want see some request response example please visit this <a href='#'>site</a>");
}
function removeGoBackInputDiv() {
$("#inputDiv").empty();
$("#btnGoBack").remove();
}
function loadDataIntoFunctionsGrid(jsonData) {
$("#mytable").append("<tr>" + "<th>function.device.UID</th>"
+ "<th>service.id</th>" + "<th>function.UID</th>" + "<th>operation.names</th>" + "<th></th>" + "</tr>");
var tr, td2, td3, td4, dt2, btn;
for(var i = 0; i < jsonData.length; i++) {
tr = "<tr>";
//#Deprecated td1 = "<td>" + jsonData[i]["CLASS"] + "</td>";
td2 = "<td>" + jsonData[i]["al.function.device.UID"] + "</td>";
td3 = "<td>" + jsonData[i]["service.id"] + "</td>";
td4 = "<td>" + jsonData[i]["dal.function.UID"] + "</td>";
//#Deprecated dt1 = fillSelectControl(jsonData[i]["objectClass"]);
dt2 = fillSelectControl(jsonData[i]["dal.function.operation.names"], i);
btn = "<td>" + "<button id='btnRunFunc"+ i + "' class='btn btn-success btn-lg'>Run</button>" + "</td></tr>";
$("#mytable").append(tr + td2 + td3 + td4 + dt2 + btn );
}
createGoBackButton();
createInputTextParameters();
}
function loadInformationFunctionsGrid() {
$("#UserGuide").addClass("alert alert-info");
$("#UserGuide").html("<h3>Getting device functions:</h3><br/>"
+ "This API is used to retrieve the list of the available functions supported by the device. For"
+ "example a Smart Plug has two functions: one to retrieve the energy consumption and another"
+ "'boolean' function useful to change the status of the smart plug (ON/OFF). Every function"
+ "indicates the id, which can be used to access directly the function and the list of the operation"
+ "that can be invoked on the function.<br/>"
+ "P.S. If he want use a function that want some parameters he must write these into the dedicated textbox. If the API needs more parameters separate these using comma. <br/>"
+ "Example of parametes: <br/> <code>'type':'java.math.BigDecimal'</code><br/> <code>'value':1</code> <br/> etc...");
}
function createGoBackButton() {
var btn = '<button id="btnGoBack" class="btn btn-warning btn-lg">Go Back</button>';
$("#goBack").append(btn);
}
function createInputTextParameters() {
var lbl ="<label>Paramters</label>";
var txt ='<input type="text" class="form-control" name="email">';
$("#inputDiv").addClass("form-group");
$("#inputDiv").append(lbl);
$("#inputDiv").append(txt);
}
function fillSelectControl(obj, id) {
var dataList = "<td><select id='slt"+ id +"'>";
for(var j = 0; j < obj.length; j++)
dataList = dataList + "<option value='" + obj[j] + "'>" + obj[j] + "</option>";
return dataList = dataList + "</select></td>";
}
var json = "";
var goBack = "";
var deviceUID;
function jsonGETRequest(url, dataExample){
$.getJSON(apiUrl, function(data) {
alert(JSON.stringify(data));
this.json = data;
})
.done(function() {
$("#information").addClass("alert alert-success");
$("#information").text("getJSON request succeeded!");
if(goBack == "") {
loadDataIntoDeviceGrid(jsonExampleData);
loadInformationDeviceGrid();
} else if (goBack=="firstAPIRequest") {
loadDataIntoFunctionsGrid(jsonExampleDataFunctions);
loadInformationDeviceGrid();
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
//alert('getJSON request failed! ' + textStatus);
$("#information").addClass("alert alert-danger");
$("#information").text("Impossible get data from API, it will be use example data" + errorThrown);
if(goBack == "") {
loadDataIntoDeviceGrid(jsonExampleData);
loadInformationDeviceGrid();
} else if (goBack=="firstAPIRequest") {
loadDataIntoFunctionsGrid(jsonExampleDataFunctions);
loadInformationFunctionsGrid();
} else if(goBack=="secondAPIRequest") {
}
})
.always(function() { });
}
function jsonPOST(url, method, paramters, dataExample) {
}
var jsonExampleData = [
{
"dal.device.status": 2,
"dal.device.UID": "ZigBee:test123",
"dal.device.driver": "ZigBee",
"service.id": 28,
"objectClass": [
"org.osgi.service.dal.Device"
]
},
{
"dal.device.status": 2,
"dal.device.UID": "ZigBee:test456",
"dal.device.driver": "ZigBee",
"service.id": 29,
"objectClass": [
"org.osgi.service.dal.Device"
]
},
{
"dal.device.status": 2,
"dal.device.UID": "ZigBee:test789",
"dal.device.driver": "ZigBee",
"service.id": 30,
"objectClass": [
"org.osgi.service.dal.Device"
]
}
];
var jsonExampleDataFunctions = [
{
"CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
"dal.function.device.UID": "ZigBee:test123",
"service.id": 27,
"dal.function.UID": "ZigBee:test123:testButton",
"objectClass": [
"org.osgi.service.dal.Function"
],
"dal.function.operation.names": [
"getData",
"reverse",
"setFalse",
"setTrue"
]
},
{
"CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
"dal.function.device.UID": "ZigBee:test456",
"service.id": 26,
"dal.function.UID": "ZigBee:test456:testButton",
"objectClass": [
"org.osgi.service.dal.Function"
],
"dal.function.operation.names": [
"getData",
"reverse",
"setFalse",
"setTrue"
]
},
{
"CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
"dal.function.device.UID": "ZigBee:test789",
"service.id": 25,
"dal.function.UID": "ZigBee:test789:testButton",
"objectClass": [
"org.osgi.service.dal.Function"
],
"dal.function.operation.names": [
"getData",
"reverse",
"setFalse",
"setTrue"
]
}
];
</script>
</body>
</html>
.is() returns a true/false value, it does not continue the jQuery chain, therefor there is no .text() function to call
As DevishOne points out in the comments to get the selected option's text do:
=$("#slt" + (parseInt(buttonElementId + 1))).children("option:selected").text();
Split that in to multiple steps and check for the particular result:
button = $("#slt" + (parseInt(buttonElementId + 1)));
if ( button )
{
childs = button.children("option");
if ( childs .....
Whenever there's no option selected, you are unable to catch that since you refer directly to a method .text() of null.

JavaScript: Assigning values from one array to variables in another

I want to populate a series of strings (beijingString, belingString etc) with values from an array ('contentStrings'); so as not to have to do:
beijingString = 'five strings';
berlinString = 'similar but different five strings';
bronxString = 'also similar but different five strings';
buenosairesString = 'similar again but subtly different five strings';
In the end I have 40 such strings to populate.
I tried putting the cities' string variable names into a second array ('cities') and looping through, assigning indexed values.
But it does not work.
Do I have to 'reference' (?) each variable as an element of the 'cities' array in some way, please?
TIA!
Full code snippet:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var beijingContentString = '';
var berlinContentString = '';
var bronxContentString = '';
var buenos_airesContentString = '';
var contentStrings = [
['http://www.beijing.com',
'Beijing title',
'<img src="./images/beijing.jpg">',
'Beijing caption',
'Beijing description'
],
['http://www.berlin.com',
'Berlin title',
'<img src="./images/berlin.jpg">',
'Berlin caption',
'Berlin description'
],
['http://www.bronx.com',
'Bronx title',
'<img src="./images/Bronx.jpg">',
'Bronx caption',
'Bronx description'
],
['http://www.buenosaires.com',
'Buenos Aires title',
'<img src="./images/Buenos Aires.jpg">',
'Buenos Aires caption',
'Buenos Aires description'
]
];
var beijingString = '';
var berlinString = '';
var bronxString = '';
var bueonosairesString = '';
alert ('before: ' + beijingString);
alert ('before: ' + berlinString);
alert ('before: ' + bronxString);
alert ('before: ' + bueonosairesString);
var cities = [beijingString, berlinString, bronxString, bueonosairesString];
var contentArrayLoop = 0;
for (contentArrayLoop = 0; contentArrayLoop < 4; contentArrayLoop++) {
cities[contentArrayLoop]=
contentStrings[contentArrayLoop][0] +
contentStrings[contentArrayLoop][1] +
contentStrings[contentArrayLoop][2] +
contentStrings[contentArrayLoop][3] +
contentStrings[contentArrayLoop][4]
;
alert(cities[contentArrayLoop]);
};
alert ('after: ' + beijingString);
alert ('after: ' + berlinString);
alert ('after: ' + bronxString);
alert ('after: ' + bueonosairesString);
</script>
</body>
</html>
A far better example is here:
http://jsfiddle.net/L1dpt0bs/1/
You don't need to use any static array for cities.
var contentArrayLoop = 0;
for (contentArrayLoop = 0; contentArrayLoop < 4; contentArrayLoop++) {
var city = contentStrings[contentArrayLoop][1]
city = city.substring(0, city.indexOf(' '));
window[city + 'string'] = contentStrings[contentArrayLoop].join('');
};
alert ('after: ' + Beijingstring);
alert ('after: ' + Berlinstring);
alert ('after: ' + Bronxstring);
alert ('after: ' + Bueonosairesstring);
This isn't all of your data, but this is a format you could use to access the information easily:
var oContentObj =
{
buenos_airesContent :
{
url : 'http://www.buenosaires.com',
title : 'Buenos Aires title',
img : '<img src="./images/Buenos Aires.jpg">',
caption : 'Buenos Aires caption',
dsc : 'Buenos Aires description'
}
}
To loop through the properties of that object, use a for.. in loop :
for (var oCity in oContentObj)
{
// now you have a loop of the cities.. do stuff
for (var oProp in oCity)
{
// Now you have the properties of the city.. do more stuff
}
}
Or you could call the properties directly
oContentObj["CityName"]["CityProp"];
// or
oContentObj.CityName.CityProp;
And for a bigger picture on handling that data on the client,
that object can become much more than a container.
It can control handling that data as well. Containing, displaying, modifying and transporting if needed. :D
You can use concept of dynamic variable
var cities = ['beijing', 'berlin', 'bronx', 'bueonosaires'];
var contentArrayLoop = 0;
for (contentArrayLoop = 0; contentArrayLoop < 4; contentArrayLoop++) {
window[cities[contentArrayLoop] + 'string'] =
contentStrings[contentArrayLoop][0] +
contentStrings[contentArrayLoop][1] +
contentStrings[contentArrayLoop][2] +
contentStrings[contentArrayLoop][3] +
contentStrings[contentArrayLoop][4]
;
};
alert ('after: ' + beijingstring);
alert ('after: ' + berlinstring);
alert ('after: ' + bronxstring);
alert ('after: ' + bueonosairesstring);
Full code is here:
http://jsfiddle.net/m745odgf/

creating a html table in javascript

I want to create HTML table in java script. Inside a for loop I want to create a dynamic table which can be extended. This is how I am it using now:
function(json)
{
var content= $('#name1').html('').append('<td> Name: ' + json.name + '<td>');
var content= $('#address1').html('').append('<td> address: ' + json.address + '<td>');
var content= $('#age1').html('').append('<td> age: ' + json.age + '<td>');
var content= $('#status1').html('').append('<td> status: ' + json.status + '<td>');
}
HTML file is
<table>
<tr id="name1"></tr>
<tr id="address1"></tr>
<tr id="age1"></tr>
<tr id="status1"></tr>
</table>
now it is just with hardcore values but I want it auto generated and insert more rows if neccessary...
remove id from tr. Because if you need multiple row then id will be duplicated which is not valid.
<table id="mytable">
</table>
function(json)
{
for(i=0;i<json.length;i++){
var newRow= $("<tr></tr>");
newRow.append('<td> Name: ' + json[i].name + '<td>');
newRow.append('<td> address: ' + json[i].address + '<td>');
newRow.append('<td> age: ' + json[i].age + '<td>');
newRow.append('<td> status: ' + json[i].status + '<td>');
$("#mytable").append(newRow);
}
}
i think this will help you
function(json)
{
for(i=0;i<jsn.length;i++){
$('#YOUR_TABLE_ID').append("<tr><td>"+ json.name+"</td></tr>")
}
}
<table id="mytable">
<tr id="name1"><td></td></tr>
</table>
if (results != null && results.length > 0) {
// Build our table header
var content = "";
for(i=0;i<data.length;i++)
{
content += '<tr>';
content += '<td></td>'
}
content += '</tr>';
}
$("#mytable tbody").append(content);
}
You can Use Append Method to create Rows in a table like
for(i=0;i<data.length;i++)
{
$("YOUR_TABLE_ID").append("<tr><td>"+data[i]['name']+"</td><td>"+data[i]['address']+"</td><td>"+data[i]['age']+"</td><td>"+data[i]['status']+"</td></tr>");
}
I'm not clear with your requirement but i can provide you some basic code hope that helps you.
var jsonList = [{name:'Jhon',address:'Jhon Address goes here',age:'27',status:'Single'},
{name:'Smith',address:'Smith Address goes here' ,age:'32', status:'Single' }];
function createTable(){
var table = '<table>';
for(var ind=0;ind< jsonList.length;ind++)
table += fetchRowInformation(jsonList[ind]);
console.log(table+'</table>');
}
function fetchRowInformation(json){
return '<tr><td> Name: ' + json.name + '<td>'+'<td> address: ' + json.address + '<td>'+ '<td> age: ' + json.age + '<td>'+'<td> status: ' + json.status + '<td></tr>';
}
JS Fiddle Demo
function tableCreate(rows, columns) {
var body = document.body
tbl = document.createElement('table');
tbl.style.width = '20%';
tbl.style.border = '1px solid black';
for (var i = 0; i < rows; i++) {
var tr = tbl.insertRow();
for (var j = 0; j < columns; j++) {
var td = tr.insertCell();
td.appendChild(document.createTextNode('Cell'));
td.style.border = '1px solid black';
}
}
tbl.style.marginTop = '10px'
tbl.style.borderCollapse = 'collapse'
td.style.padding = '2px'
body.appendChild(tbl);
}
tableCreate(15, 10);

Categories