How do I add data into html table using jquery? - javascript

I'm trying to add data from my firebase realtime database into a html table using jquery and javascript. I'm new to jquery, so I more or less have no idea what I'm doing.
I can retrieve the data but I can't add it to the table on the html page.
Is something wrong with this line?:
$("#table_body tbody").append("<tr><td>" + name.Name + "</td><td>" +
user.Email + "</td></td></td></tr>");
the table_body is just the table's id. The table remains empty.
pls help

You can add things to a table like this:
function productsAdd() {
$("#productTable tbody").append(
"<tr>" +
"<td>My First Item</td>" +
"<td>6/11/2019</td>" +
"<td>www.itemsite.com</td>" +
"</tr>"
);
}

Is this code running on load? Is this code wrapper in:
$(document).ready(function(){});
The document must be loaded before jQuery code can run properly, the function above ensures jQuery inside of it runs after the DOM has loaded
Example:
$(document).ready(function() {
let arr = [{n:'test', e:'ing'}, {n:'stuff', e:'ok'}];
for(let i = 0; i < arr.length; i++) {
$("#table_body tbody").append("<tr><td>" + arr[i].n + "</td><td>" + arr[i].e + "</td></tr>");
}
});

Related

The html td is not updating via jquery

I have this little method which, on the first load, created a <tr> and some <td>'s. That works. But if the underlying data changes, the <td>'s are not updated. I'm not sure why.
function ParseJson(json, isFirstLoad)
{
json = $.parseJSON(json);
var tr;
for (var i = 0; i < json.length; i++) {
if (isFirstLoad === 1)
{
tr = $('<tr/>');
tr.append("<td id='" + json[i].LocationName + "'>" + json[i].LocationName + "</td>");
tr.append("<td id='" + json[i].LocationName + "Count'>" + json[i].Count + "</td>");
$('#MainTable').append(tr);
}
else
{
var td = $("#" + json[i].LocationName + "Count");
td.html = json[i].Count;
}
}
When isFirstLoad is 1, the html is rendered as I would expect. Example:
<tr>
<td id="ChemLab">ChemLab</td>
<td id="ChemLabCount">24</td>
</tr>
But the next time around, if the data has changed and someone has left the Chem Lab, the html for ChemLabCount does not change.
I have verified that the json being passed into this method is correct. Meaning, the count DOES indeed change. It just doesn't get displayed on the screen.
jQuery .html() is a function, not a property.
td.html(json[i].Count);
The problem comes from td.html = json[i].Count; because it's not the right way of using html() method.
To set the Count to your td you could use .text() instead :
td.text( json[i].Count );
Else if you want to set an HTML code the you could use .html() :
td.html( json[i].Count );

jQuery getJSON and get value from button

I'm download data from JSON file and display button with value:
function iterateOverPrzepisy(best) {
$('#listaPrzepisow').html('');
$.getJSON('przepisy.json', function(data) {
for (var x in przepisyDost) {
$('#listaPrzepisow').append(" <div data-role=\"collapsible\"><h2>" + przepisyDost[x].nazwa + "</h2>" +
"<ul data-role=\"listview\" data-theme=\"d\" data-divider-theme=\"d\">" +
"<li>" +
"<h3>Składniki: " + przepisyDost[x].skladniki + "</h3>" +
"<p class='ui-li-desc' style='white-space: pre-wrap; text-align: justify;'>" + przepisyDost[x].tresc + "</p>" +
"<button id='ulubioneBtn' value='" + przepisyDost[x].id + "'>Ulubione</button></li>" +
"</ul>" +
"</div>");
j++;
}
})
}
When I click to button #ulubioneBtn I would like to get value from this button. So I add done to getJSON
}).done(function(data){
$('button#ulubioneBtn').click(function (event) {
console.log("Ulubione: ");
event.preventDefault();
var id = $("button#ulubioneBtn").val();
console.log("Value: " + id);
//dodajemy do ulubionych
localStorage.setItem("ulubione"+id, id);
});
});
But it's not working. When I click on button Ulubione I always get in console log value = 0
The problem seems to be that you add multiple buttons with the same id. An id of a html element should be unique.
przepisyDost does not appear to be defined at
for (var x in przepisyDost) {
? Try
for (var x in data.przepisyDost) {
Duplicate id's are appended to document at
"<button id='ulubioneBtn' value='" + przepisyDost[x].id
+ "'>Ulubione</button></li>" +
within for loop. Try substituting class for id when appending html string to document
"<button class='ulubioneBtn' value='" + data.przepisyDost[x].id
+ "'>Ulubione</button></li>" +
You could use event delegation to attach click event to .ulubioneBtn elements, outside of .done()
$("#listaPrzepisow").on("click", ".ulubioneBtn", function() {
// do stuff
})
I have created a dummy JSON and executed the same JS with a single change.
In onclick handler instead of getting button I am using $(event.target).
And it is working fine.
Please find the fiddle https://jsfiddle.net/85sctcn9/
$('button#ulubioneBtn').click(function (event) {
console.log("Ulubione: ");
event.preventDefault();
var id = $(event.target).val();
console.log("Value: " + id);
//dodajemy do ulubionych
localStorage.setItem("ulubione"+id, id);
});
Seems like first object doesn't have any id value.
Please check JSON response returned from server.
Hope this helps you in solving.

jQuery selector unable to find table row class

Given an array of strings returned from an sql query, I am appending the data as rows into my html table via javascript:
loadUsers: function()
{ .
.
.
function displayUsersOnTable(response)
{
for(var i = 0; i < response.results.length; i++)
{
var contact = response.results[i];
var $newRow = $('<tr class="user-row">' +
'<td>' + contact.full_name + '</td>' +
'<td>' + contact.email + '</td>' +
'</tr>')
.data('user', contact);
$userTableBody.append($newRow);
}
}
}
Inside a different function that is called after loadUsers is called, I have this:
$('.user-row').click( function() {
window.alert("CLICKED");
});
When I run my site it won't register the click event. If I select the classes from my table row or table header it runs fine. I suspect the problem involves the fact that the table rows are dynamically generated. When I inspect element everything is in place. What am I missing?
try:
$(document).on('click', '.user-row', function() {
window.alert("CLICKED");
});

Jquery addEventListener in Chrome with parameters

A feature was developed in an application by clicking a hyperlink in a table, open a div below with a table, filtering contents, depending on the link.
The link was created dynamically in one jQuery function and had the following attributes:
$("#pending div#list").bind("data_loaded", function (event, records) {
var tableBody = $("tbody", $(this));
for (var index = 0; index < records.length; index++) {
var rowHtml = '<tr id="' + rowid + '"><input type="hidden" name="' + rowid + '" id="' + rowid + '" value="1"/>' +
'<td><a class="populate" id="' + rowid + '" onclick="javascript:clickHandler(' + rowid + ');">' + docid + '</a></td>' +
'</tr>';
tableBody.append($(rowHtml));
}
});
In Mozilla Firefox, it works perfectly fine. However in Chrome I cannot call the clickHandler function.
From the information I find on Google, say Inline JavaScript will not be executed.
You can check here: https://developer.chrome.com/extensions/contentSecurityPolicy
But now comes my difficulty.
I changed my hyperlink to:
'<td><a class="populate" id="' + rowid + '" onclick="clickHandler(' + rowid + ');">' + docid + '</a></td>' +
And I created this jQuery:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById([parameter]).addEventListener('click', function () { clickHandler([parameter]); },false);
});
Can anyone explain how I can pass the parameter rowid for jQuery?
Thanks.
Regards.
Your snippets imply you're using raw DOM manipulation in Javascript rather than JQuery (which is good! it's definitely faster) but since you mention JQuery, that's what I'll be suggesting.
Instead of your addEventListener call above, try
$('div#list').on('click', 'a.populate', function() {
clickHandler($(this).attr('id'));
});
And then remove the 'onclick' attribute in the declarations of the anchor tags too.
This will add an event listener to all anchor tages with a class of 'populate' which will call clickHandler passing a string parameter consisting of that anchor tag's 'id'.

How do I execute an event using jQuery through an html object(button) created through Javascript?

I'm just new here. So here's where I'm stuck:
I created an html table using javascript. I have a button,which when clicked, will create set of tables with exactly the same structure but the objects(eg. button, text) inside those tables have different ID's. Now when I try to execute a click function using jQuery with a button on one of the produced tables, it won't work. How do I go around here? Thanks in advance!
Here's a sample function which creates the html table(with unique ID's) in javascript:
function CreateTables() {
var html = ' ';
var valPrompt = prompt("How many tables would you like to add?");
parseInt(valPrompt);
for (i = 1; i <= valPrompt; i++) {
html += "<table>" + "<tr>" + "<td>" + "Text goes here" + "</td>" + "<td>" + "<input type='text' id='txtTEXT" + i + "'/>" + "</td>" + "<td>" + < input type = 'button'
id = 'btnALERT" + i + "' / > +"</td>" + "</tr>" + "</table>"
}
document.getElementById('HtmlPlaceHolder').innerHTML = html;
}​
So, if we review the code, Sets of table with buttons(btnALERT) with unique ID's will be created if the function CreateTables is executed. In order to select the objects, I suppose I'll be using jQuery. So for example, if I bind a handler in btnALERT1(produced by CreateTables) say a click function in order to alert a simple "Hello", how will I do this? My code for this doesn't seem to work:
$(document).ready(function() {
$('#btnALERT1').click(function() {
alert("Hello");
});
});​
Use .live() (for older jquery versions - < v1.7):
$('#btnALERT1').live('click', function()
{
alert("Hello");
});
Or:
$(document).delegate('#btnALERT1', 'click', function()
{
alert("Hello");
});
Use .on() (for new jquery versions - >= 1.7):
$(document).on('click', '#btnALERT1', function()
{
alert("Hello");
});
I think you may want to use the method .on():
$(document).ready(function() {
$('#btnALERT1').on('click', function() {
alert("Hello");
});
});
For more information, check the online doc: http://api.jquery.com/on/
I would use a delegate on HtmlPlaceHolder to check for click events like so:
$("#HtmlPlaceHolder").on("click", "input[type=button]", function() {
alert($(this).attr("id"));
});
Also, I would change the button id scheme to btnALERT_1, so you can extract the ID number with a .split("_") method.
You have to attach the event handlers after you create the tables, not when the document is ready (the document should be ready anyways since the user is interacting with it).
You can do this with jQuery, sure, but have a look at the native methods - jQuery might be too bloated depending on what you will do and you will learn something about the DOM.
I've added some code below which lets you add a callback and shows some things you can get back easily. It is not exactly what you asked for, but a great start to finding your way in the DOM.
function CreateTables() {
var html = ' ';
var valPrompt = prompt("How many tables would you like to add?");
parseInt(valPrompt);
for (i = 1; i <= valPrompt; i++) {
html += "<table>" + "<tr>" + "<td>" + "Text goes here" + "</td>" + "<td>" + "<input type='text' id='txtTEXT" + i + "'/>" + "</td>" + "<td>" + < input type = 'button'
id = 'btnALERT" + i + "' / > +"</td>" + "</tr>" + "</table>"
}
var placeholder = document.getElementById('HtmlPlaceHolder').innerHTML = html;
placeholder.innerHTML = html;
placeholder.addEventListener('click', function (e) {
console.log(this, e);
}
}​

Categories