Okay, so i am pulling data from a json file and at the same time i am putting them in to a table. I've managed to give every td item a dynamic id. However, that id is only accessible inside the html and when i try to use for a function it is either undefined or it is getting the length of every row but not the id.
<script type='text/javascript'>
var dynID;
$(function() {
var data = [];
$.getJSON( 'f-data.json', function(data) {
$.each(data.data, function(i, f) {
var tblRow = "<tr><th>" + '<td id = "editable'+this.id+'">' + f.Title+ "</td></th>";
dynID = $(this).find("td").attr("id");
tblRow += '<th colspan="2"><button type ="submit" class="edit" onclick="editButton(dynID)"></i></button>';
$(tblRow).appendTo(".screens tbody");
});
});
});
<script type='text/javascript'>
function editButton(id) {
alert(id);
}
JSON :
{ "data":[
{
"Title": "Screen 1",
"id": 1
},{
"Title": "Screen 2",
"id": 2
}
The above produces a button and when the button is pressed the result is undefined. The strange thing is that the id's are generated correctly (e.g. editable1, editable2, etc). I guess am not selecting the id correctly?
You are running into reference issues within the $.each loop. Within the loop, the reference to $(this) is a jQuery object made of the element of data array. It does not have any HTML. I believe you meant to treat/parse tblRow as jQuery object and extract the id from it. Doing this is bad for performance. your current code simply the output of the button is:
<button onclick="editButton(dynID)"></button>
This is because dynID is becoming a part of the string -- there is no concatenating happening here. Hence, the output becomes a reference to a variable named dynID in the global scope window.
I would rewrite that code as below.
$.each(data.data, function(i, f) {
var id = this.id, // use id accross the loop.
tblRow = "<tr><th>" + '<td id = "editable' + id +'">' + f.Name + "</td></th>";
tblRow += '<th colspan="2"><button type ="submit" class="edit" onclick="editButton("' + id + '")"></i></button>';
$(tblRow).appendTo(".screens tbody");
});
Related
I got a situation where I would like to read some data off a JSON format, however I am having some issues understanding how I should construct the button dynamically from JSON object.
My scenario is as follows:
$(document).ready(function() {
var socket = io.connect('http://' + document.domain + ':' + location.port);
// listen for mqtt_message events
// when a new message is received, log and append the data to the page
socket.on('mqtt_message', function(data) {
var json = JSON.parse(data['payload']);
var table = $("<table>");
table.append($("<tr><th>Host</th><th>Name</th><th>ID</th><th>"));
for (var i = 0; i < json.length; i++) {
var row = $("<tr><td>" + json[i]["name"] + json[i]["ID"] + "</td></tr>");
table.append(row);
}
table.appendTo($("#container"));
})
});
where
json = {"host":abc,"name":123,"id":345}
I have to make hostname as button and when I click on that button for example here, name "abc", i will get details name and id in table format. I have created table but it is showing whole table not that scenario which I actually want.
I am new to the JavaScript, facing issues here.
1) The JSON data doesn't seem to be an array, you can't loop through it.
2) You have to append the header to a <thead> element.
3) You have to append the table row to a <tbody> element.
All tables should have a <thead> and a <tbody> element, so just add it to your HTML code.
<div id="container">
<table style="display:none">
<thead>
<tr>
<th>Host</th>
<th>Name</th>
<th>ID</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
Then you append your data to these HTML elements, like so. If your data is an object and not an array, just don't loop through it but instead call the properties as is.
var json = [{
host: "Some host IP",
name: "Some name",
id: 345
},
{
host: "Some other host IP",
name: "Some other name",
id: 987
}
];
var $container = $("#container");
var $thead = $("#container table thead");
var $tbody = $("#container table tbody");
var $row = $("#container table tbody tr");
// Loop through items in JSON data..
json.forEach(function(item) {
var $button = $("<button>" + item.host + "</button>");
$container.prepend($button);
// Button click handler..
$button.on("click", function() {
// Replace row HTML..
$row.html('<td>' + item.host + '</td>' + '<td>' + item.name + '</td>' + '<td>' + item.id + '</td>');
// Show table if it's not already visible..
$("#container table").show();
});
});
Full code here:
https://jsfiddle.net/amsv/15h74uy6/
Vanilla JS, ie. without jQuery:
https://jsfiddle.net/amsv/15h74uy6/72/
let json = [
{"host":abc,"name":123,"id":345},
{"host":def,"name":456,"id":345}
]
In your html write
<button *ngFor = 'let item of json' (click)='buttonOnClick($event)'>
{{item.host}}
</button>
Above code will render two buttons for each element in the array
In your ts write
buttonOnClick(event) {
console.log(event) // you will get the corresponding object from the array
}
var sampleData = [{ "host": "abc", "name": 123, "id": 345 }, { "host": "xyz", "name": 456, "id": 678 }]
When data is received you should create button which shows table and set data attribute of button with received data.
for (var i = 0; i < sampleData.length; i++) {
var item = sampleData[i];
var button = $('<button />');
button.text(item.host);
button.data('data', JSON.stringify(item))
button.on('click', function (e) {
e.preventDefault();
showTable(e);
});
$('#buttons').append(button);
}
showTable is like as below
function showTable(e) {
var json = JSON.parse($(e.target).data('data'));
var table = $("<table>");
table.append($("<tr><th>Host</th><th>Name</th><th>ID</th><th>"));
var row = $("<tr><td>" + json["host"] + "</td><td>" + json["name"] + "</td><td>" + json["id"] + "</td></tr>");
table.append(row);
$("#table").html(table);
}
Html is below:
<div id="container">
<div id="buttons">
</div>
<div id="table">
</div>
</div>
I've created a table using an AJAX request to the database of items in our inventory displaying a picture/part name/price/stock remaining. When the table displays I would like to be able to click on any part of one of the rows and have it link to the item page associated with that item but it won't work.
I've tried the on.click with a static table written right into the html and it worked fine. Also if I direct the on.click script to just the table id instead of the table id and tr i can make the entire table clickable to the first row's href. So it appears that since the tr doesn't really exist in the html the javascript won't find it. Is there a way to get the script to recognize each 's href attribute?
HTML CODE + on.click script:
<html>
<body>
<table id="ctable">
<tbody id="tbody1" class="tbody1">
</tbody>
</table>
<script>
$('#ctable tr').click(function() {
var href = $(this).find("a").attr("href");
if(href) {
window.location = href;
}
});
</script>
</body>
</html>
.JS File CODE that creates table from .php file/mysql database
document.addEventListener('DOMContentLoaded', function() {
$.post('test.php', function(data) {
$("#tbody1").empty();
$.each(JSON.parse(data), function (index, value){
var eachrow = "<tr>" +
"<td class=\"image\">" + '<img src="images/thumbs/' +
value.image + '">' + "</td>" +
"<td>" + '<a href="' + value.link + '">' + value.part + "
</td>" +
"<td>" + value.price + "</td>"
"<td>" + value.stock + "</td>"
"</tr>";
$('#tbody1').append(eachrow);
});
});
}, false);
If you are dynamically adding rows, you need to either restructure your click event to listen from the context of the parent as in:
$("#tbody1").on("click", "tr", function(e) {
});
Assuming #tbody1 is a good place to start since you probably don't want the header row to be clickable. Or, every time you dynamically add rows, since the code is rebuilding the table, you can reattach the click event handlers:
$("#tbody1").empty();
$.each(JSON.parse(data), function (index, value){
var eachrow = "..
$('#tbody1').append(eachrow);
});
// or .on("click", function() { })
$("#tbody1 tr").click(function() { });
If you attach click handler via on, it would be good to then do an off as in:
$("#tbody1").off("click", "tr");
To remove the existing click handlers.
I am dynamically constructing table rows using jquery.
In the following chunk of code, how do I read someValue in method prepareDiv()?
$( document ).ready(function() {
var someValue = "DummyValue"
html += '<tr id="resRowId' + rowindex + '" class="RsrvnRowClass">' +
'<td><a href="#" onclick="prepareDiv('+ someValue +');"><img src="../images/downarrow.jpg"></td></tr>';
$('#resTable tr').first().after(html);
});
function prepareDiv(value){
alert("value" + value);
}
I am using IE. Upon calling ready(), I get error DummyValue is undefined.
The problem is that you're ending up with generated code that looks like this:
onclick="prepareDiv(DummyValue);"
The lack of quotes around DummyValue means that it's expected to be a variable, whereas you want it to be treated as a string literal, so you need to add the quotes yourself:
onclick="prepareDiv(\''+ someValue +'\');"
That should result in:
onclick="prepareDiv('DummyValue');"
Just do something like this...the dynamically added values should be appended to tbody
var table = $("table tbody");
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
firstVal= $tds.eq(0).text(),
secVal = $tds.eq(1).text(),
thirdVal = $tds.eq(2).text();
alert(firstVal);//etc..
});
You have fews syntax errors, try this:
$( document ).ready(function() {
var someValue = "DummyValue";
html += '<tr id="resRowId' + rowindex + '" class="RsrvnRowClass">' +
'<td>' + '<img src="../images/downarrow.jpg" /></td></tr>';
$('#resTable tr').first().after(html);
});
I am trying to create a HTML table like the following dynamically using jQuery:
<table id='providersFormElementsTable'>
<tr>
<td>Nickname</td>
<td><input type="text" id="nickname" name="nickname"></td>
</tr>
<tr>
<td>CA Number</td>
<td><input type="text" id="account" name="account"></td>
</tr>
</table>
This is my actual table :
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
This is the method which will create tr and td elements taking id and labelText:
function createFormElement(id, labelText) {
// create a new textInputBox button using supplied parameters
var textInputBox = $('<input />').attr({
type: "text", id: id, name: id
});
// create a new textInputBox using supplied parameters
var inputTypeLable = $('<label />').append(textInputBox).append(labelText);
// append the new radio button and label
$('#providersFormElementsTable').append(inputTypeLable).append('<br />');
}
I also have a value which will be shown as tool tip.
Please help me to create a table dynamically with tool tip and tr td.
EDIT:
I have almost done with the following code:
function createProviderFormFields(id, labelText,tooltip,regex) {
var tr = '<tr>' ;
// create a new textInputBox
var textInputBox = $('<input />').attr({
type: "text",
id: id, name: id,
title: tooltip
});
// create a new Label Text
tr += '<td>' + labelText + '</td>';
tr += '<td>' + textInputBox + '</td>';
tr +='</tr>';
return tr;
}
Here label is coming properly and the input box is not coming and it shows [object Object] where the text box has to come...
When I printed the textInputBox using console.log, I get the following:
[input#nickname, constructor: function, init: function, selector: "", jquery: "1.7.2", size: function…]
What could be the issue?
Thanks to #theghostofc who showed me path... :)
You may use two options:
createElement
InnerHTML
Create Element is the fastest way (check here.):
$(document.createElement('table'));
InnerHTML is another popular approach:
$("#foo").append("<div>hello world</div>"); // Check similar for table too.
Check a real example on How to create a new table with rows using jQuery and wrap it inside div.
There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.
Edit:
Check Dynamic creation of table with DOM
Edit 2:
IMHO, you are mixing object and inner HTML. Let's try with a pure inner html approach:
function createProviderFormFields(id, labelText, tooltip, regex) {
var tr = '<tr>' ;
// create a new textInputBox
var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';
// create a new Label Text
tr += '<td>' + labelText + '</td>';
tr += '<td>' + textInputBox + '</td>';
tr +='</tr>';
return tr;
}
An example with a little less stringified html:
var container = $('#my-container'),
table = $('<table>');
users.forEach(function(user) {
var tr = $('<tr>');
['ID', 'Name', 'Address'].forEach(function(attr) {
tr.append('<td>' + user[attr] + '</td>');
});
table.append(tr);
});
container.append(table);
Here is a full example of what you are looking for:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='nickname' name='nickname'></td></tr><tr><td>CA Number</td><td><input type='text' id='account' name='account'></td></tr>");
});
</script>
</head>
<body>
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
</body>
I understand you want to create stuff dynamically. That does not mean you have to actually construct DOM elements to do it. You can just make use of html to achieve what you want .
Look at the code below :
HTML:
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'></table>
JS :
createFormElement("Nickname","nickname")
function createFormElement(labelText, id) {
$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='"+id+"' name='nickname'></td><lable id='"+labelText+"'></lable></td></tr>");
$('#providersFormElementsTable').append('<br />');
}
This one does what you want dynamically, it just needs the id and labelText to make it work, which actually must be the only dynamic variables as only they will be changing. Your DOM structure will always remain the same .
WORKING DEMO:
Moreover, when you use the process you mentioned in your post you get only [object Object]. That is because when you call createProviderFormFields , it is a function call and hence it's returning an object for you. You will not be seeing the text box as it needs to be added . For that you need to strip individual content form the object, then construct the html from it.
It's much easier to construct just the html and change the id s of the label and input according to your needs.
FOR EXAMPLE YOU HAVE RECIEVED JASON DATA FROM SERVER.
var obj = JSON.parse(msg);
var tableString ="<table id='tbla'>";
tableString +="<th><td>Name<td>City<td>Birthday</th>";
for (var i=0; i<obj.length; i++){
//alert(obj[i].name);
tableString +=gg_stringformat("<tr><td>{0}<td>{1}<td>{2}</tr>",obj[i].name, obj[i].age, obj[i].birthday);
}
tableString +="</table>";
alert(tableString);
$('#divb').html(tableString);
HERE IS THE CODE FOR gg_stringformat
function gg_stringformat() {
var argcount = arguments.length,
string,
i;
if (!argcount) {
return "";
}
if (argcount === 1) {
return arguments[0];
}
string = arguments[0];
for (i = 1; i < argcount; i++) {
string = string.replace(new RegExp('\\{' + (i - 1) + '}', 'gi'), arguments[i]);
}
return string;
}
I cannot figure out for the life of me why this will not work. I am trying to pull the value of a textfield that was created with a loop from a json file.
In this code, at the very bottom I just do a simple click(function() {alert()} just to see if I can pull a value and its returning undefined. But if I remove '#name' and put in 'input' it captures it, but only for the first of several input fields.
Any help is really appreciated
JSON
{
"Controls": [{
"Button":[{ "Name":"Button", "x": "1","y": "2","width": "3","height": "4","Transition":"" }],
"Image":[{"x": "5","y": "6","width": "7","height": "8"}],
"TextField":[{"x": "9","y": "10","width": "11","height": "12","Rows":""}]
}]
}
The Code(there is soome getJSON stuff above this)
//Slide In Attributes Panel Based on Selected Object
$(document).on('click', '#code li', function () {
var index = $('#code li').index(this);
var selected = $(this).text();
switch (selected) {
case selected:
$('#options').hide();
hidePanels();
$('#temp').remove();
$('#objectAttributes').show("slide", 200);
break;
//If it does work show what variable is being used
default:
alert(selected);
break;
}
//Shows Selected LI Index
$('#codeIndex').text("That was div index #" + index);
//Pull list of Attributes for selected Object
$.getJSON('controls.json', function (data) {
//Build Attributes List
var attributeList = '<div id="temp">';
//Target based on selected object
var target = selected;
attributeList += '<div>' + target + '<div>';
$.each(data.Controls[0][target][0], function (kk, vv) {
attributeList += '<div style="float:right">' + kk + ':' + '<input type="text" id='+ kk + '>' + '</input>' + '</div>';
});
attributeList += '</div></div>';
attributeList += '</div>';
$('#objectAttributes').append(attributeList);
$('#temp').append('<div id="editIndex">'+"Modifying index" + " " +index+'</div>');
$(document).on('click', '#saveAttributes', function () {
var $x = $('#name').val();
alert($x);
})
});
});
Ok, so after a little hacking around with a jsfiddle the answer turned out to be a lot simpler than I first thought. Ever since HTML 4.01 class names and IDs have been case sensitive (reference), which means that your selector $('#name') wasn't matching the JSON Name.
So a simple change, such as in this simplified jsfiddle seems to work as desired. Hopefully this helps!