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");
});
Related
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>");
}
});
The purpose of this code is to make an ajax call if the <td> contained within the <tr> that is below the <tr> that was clicked, but only if the hidden <tr> is empty. Eventually I plan to take that data and do something with it, but for right now, I just need to get this thing which emulates an accordion as a table working. Due to this table being made on the same html file that I have other .hidden elements on, I had to create custom classes to hide these particular ones. The class detail-view makes it visible, and the class hidden-detail contains display:none. I know that postDetails works as far as finding the right data. What i'm more worried about is finding out why FireFox's dev tools say statusRow and detPane are marked as (unavailable) throughout this code, whereas statusRow.closest('tr').next('tr') actually appears to contain the row detPane, as intended. Is there something wrong with the jQuery or selectors? What's going on here?
function makeOrderTable(response, username, sesstoken) {
$(jQuery.parseJSON(JSON.stringify(response))).each(function() {
var foNum = this['Factory Order#'];
var pO = this['PO#'];
var status = this['Status'];
var shipDate = this['Ship Date'];
$('.orders tbody').append(
'<tr class="status-row">'+
'<td>' + foNum + '</td><td>' + pO + '</td><td>' + status + '</td><td>' + shipDate + '</td>'+
'</tr>'+
'<tr class="detail-row hidden-detail">'+
'<td colspan="4"></td>'+
'</tr>'
);
});
$(document).ready(function() {
$('table').on('click', 'tr.status-row', function() {
var statusRow = $(this);
var detPane = $(statusRow[0]).closest('tr').next('tr');
$('.detail-view').addClass('hidden-detail');
$('.detail-view').removeClass('detail-view');
detPane.addClass('detail-view');
detPane.removeClass('hidden-detail');
if (detPane.find('td').text == '')
{
var value = statusRow.find('td:first-child').text();
postDetails(value, username, sesstoken, detPane.find('td'));
}
});
});
}
The problem was that as epascarello pointed out, text isn't a valid property. Ergo, couldn't find anything. But, I also needed to grab the details td separately--i.e. couldn't access things from other things and just daisy-chain selectors all over the place. So, here's the end result.
function makeOrderTable(response, username, sesstoken) {
$(jQuery.parseJSON(JSON.stringify(response))).each(function() {
var foNum = this['Factory Order#'];
var pO = this['PO#'];
var status = this['Status'];
var shipDate = this['Ship Date'];
$('.orders tbody').append(
'<tr class="status-row">'+
'<td>' + foNum + '</td><td>' + pO + '</td><td>' + status + '</td><td>' + shipDate + '</td>'+
'</tr>'+
'<tr class="detail-row hidden-detail">'+
'<td colspan="4"></td>'+
'</tr>'
);
});
$(document).ready(function() {
$('table').on('click', 'tr.status-row', function() {
var statusRow = $(this);
var detRow = statusRow.closest('tr').next('tr');
var details = this.nextElementSibling.querySelector('td');
$('.detail-view').addClass('hidden-detail');
$('.detail-view').removeClass('detail-view');
detRow.addClass('detail-view');
detRow.removeClass('hidden-detail');
if (details.innerText == '')
{
var value = statusRow.find('td:first-child').text();
postDetails(value, username, sesstoken, details);
}
});
});
}
If I understand the question correctly, I think your selector for the "hidden" tr is incorrect.
You have the click event attached to the tr, so you shouldn't have to do .closest('tr'). Just var detPane = $(statusRow[0]).next('tr'); should get you the next tr after the one that was clicked.
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.
This is the code which i use to append table row,where personTabs is the iframe name
$(".addClass1").on('click',function() {
parent.parent.parent.personTabs.$("#skilltableId").append(
'<tr id="skilltableId1"><td class="btnRemoving">'+$("#selecetedValue").val()+'</td><td class="editing">'+$("#type").val()+'</td><td style="display:none">'+$("#commonDbid").val()+'</td></tr><br>'
);
when i click td class='editing', i am generating a textbox as follows..
parent.parent.parent.personTabs.$(".editing").on('click',function() {
var data = $(this).text();
$(this).html("<input type='text' id='focus123' value='"+data+"'/>").children().focus();
});
I am getting everything fine for the first time..the table row is been appended fine..when i do the same append for the second time,table row is generated.onclick working only for the last generated row..but not previous one..why is it so..anybdy here can tel me,..i tried live,delegate methods..but none worked..i am using jquery-1.9.1.js
I think one problem is that you have created a text box with the same id.
I am not sure why you used parent.parent.parent...
$(".addClass1").on('click',function() {
$("#skilltableId").append(
'<tr id="skilltableId1"><td class="btnRemoving">'+$("#selecetedValue").val()+'</td><td class="editing">'+$("#type").val()+'</td><td style="display:none">'+$("#commonDbid").val()+'</td></tr><br>'
);
$(".editing").on('click',function() {
var data = $(this).text();
$(this).html("<input type='text' class='focus123' value='"+data+"'/>").children().focus();
});
I am not sure if it will work or not, but you can also use this javascript function
$(".addClass1").on('click', function () {
$("#skilltableId").append('<tr id="skilltableId1"><td class="btnRemoving">' + $("#selecetedValue").val() + '</td><td class="editing" on click="myfunction(this)">' + $("#type").val() + '</td><td style="display:none">' + $("#commonDbid").val() + '</td></tr><br>');
function myfunction(selectedTd) {
var data = $(selectedTd).text();
$(selectedTd).html("<input type='text' class='focus123' value='" + data + "'/>").children().focus();
}
});
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);
}
}