After receiving the data via JSON and add content on a table, was used the event delegation to capture the links of this content, but when you click the link that was created dynamically want to access the prev () the tr element containing the data-id. But this is me returning undef. Can someone help me? The prev() is being called by editarComercial()
Javascript:
$(document).ready(function(){
function editarComercial(trthis) {
alert($(trthis).prev().prev().data('id'));
}
function listaComercial(){
url = BASE_URL + 'comercial/ajaxrequest/listagem';
$.getJSON(url,function(data){
var trs = [];
$.each(data,function (key){
tr = "<tr data-id=\""+data[key].id+"\">";
tr += "<td>"+data[key].nome+"</td>";
tr += "<td>Editar";
tr += "Excluir</td>";
tr += "</tr>";
trs.push(tr);
});
$("<tbody/>",{
html: trs.join("")
}).appendTo("#listagemComercial");
});
}
$(document).on('click','a.edit-comercial',function(){
editarComercial(this);
});
listaComercial();
});
HTML:
<div id="content">
<table id="listagemComercial">
<thead>
<tr>
<th>Nome</th>
<th>Ações</th>
</tr>
</thead>
</table>
</div>
.edit-comercial doesn't have a previous element, it's the first element in the TD.
You probably wanted closest() instead, to traverse up to the row
function editarComercial(trthis) {
alert( $(trthis).closest('tr').data('id') );
}
Related
I have an array of objects being displayed in a table... My goal is to access a specific item within the array by clicking on that item in the table. I would then be able to add/remove classes and access the values, which is ultimately what I need to do.
Here's where I'm stuck...
myArray.forEach((item, index) => {
// Sort through array, render to DOM
document.getElementById('myElementID').innerHTML +=
'<tr>' +
'<td>' +
item.thing +
'</td>' +
'<td' +
item.thing2 +
'</td>' +
'</tr>';
// Completely stuck... I've added an event listener to each table row.
addEventListener('dblclick', () => {
console.log(//I want to log the index of the item I just clicked on);
});
});
Please forgive me if this is very easy or I'm going about this all wrong, but I'm very new to all of this and I haven't been able to structure my question in such a way that google is helpful.
Thanks in advance.
EDIT - Some html as requested...
<table id="myElementID">
<tr>
<th id="heading">Heading1</th>
<th id="anotherHeading">Heading2</th>
</tr>
</table>
EDIT again (sorry) ... and a JS fiddle. You'll see that it logs both indexes, instead of just the one I clicked on. https://jsfiddle.net/c4pd5wmg/4/
Instead of messing with index etc.. you can attach the event handler to the tr and just reference e.target in the event handler. I also cleaned up your adding of tr.
const myArray= [{number: 45,otherNumber: 55},{number: 48,otherNumber:58}]
myArray.forEach((item, index) => {
let row = document.createElement("tr");
let cell = document.createElement("td");
cell.innerHTML = item.number;
row.appendChild(cell);
cell = document.createElement("td");
cell.innerHTML = item.otherNumber;
row.appendChild(cell);
document.getElementById('myElementID').appendChild(row);
row.addEventListener('dblclick', (e) => {
console.log(e.target);
});
});
<table id="myElementID">
<tr>
<th id="heading">Heading1</th>
<th id="anotherHeading">Heading2</th>
</tr>
</table>
I have a html table
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
data here <3 ....
</tbody>
</table>
and here is my php (sample.php)
<?php
Query Code here..
Query Code there..
and so on
//this is the way I populate a table
while (query rows) {
echo '<tr>';
echo '<td>Sample Data</td>';
echo '</tr>;
}
?>
So to make this work and to populate the table this is what I do.
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
<?php
include 'folder_location/sample.php';
?>
</tbody>
</table>
Disregard the image of the ouput but when I go to Inspect Element or even Ctrl + u I will see my table structure now is like this.
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
<tr>
<td>Sample Data</td>
</tr>
</tbody>
</table>
Now here is the thing. I do not do that this is what I do.
$("#rpttable tr").remove();
for (i = 0; i < data.length; i++) {
tr = $("<tr />");
for (x in data[i]) {
td = $("<td />");
td.html(data[i][x]);
tr.append(td);
}
rpttable.append(tr);
}
Same output It does populate the table but when I go to Inspect Element or even Ctrl + u the output is.
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
**This is the part missing**
</tbody>
</table>
My question here is how can I literaly create an element usung javascript/ajax? same output in php. I mean write the element.
** Updated **
I am trying to run a css class from an external file and If I manualy edit it to suits my needs I will a long hour and also Its hard for me to explain its a class for table. I tried to use that class using default value in <table>. You know manualy write it at the back end. now Im trying to populate it using a php and ajax so, so far so good it does populate but when I try to run the class the class does not work.
TYSM
Using jquery you can add html rows to the tbody using:
$("#rptbody").html("<tr><td>value</td></tr>");
Is this what you want to do?
You can use JQuery append() method:
$('#rptbody').append('<tr><td>my data</td><td>more data</td></tr>');
In case you need to insert after last row:
$('#rptbody> tbody:last-child').append('<tr>...</tr><tr>...</tr>');
for (i = 0; i < 5; i++) {
let tr = $("<tr />");
for (j=0; j < 5;j++)
tr.append($("<td />",{html:j,class:"tbl"}));
$("tbody").append(tr);
}
.tbl{border:1px solid pink;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody></tbody>
</table>
You have asked roughly two questions. Let's break it down.
My question here is how can I literaly create an element usung javascript/ajax?
You are already doing this with your Javascript (client-side) code. It looks like you're using jQuery syntax, so we'll stick with that. This does create an element and inserts it into the page.
var $el = $("<div>I'm a new div element</div>");
$('body').append( $el );
This creates a new element, assigns it to the $el variable, and then appends it to the body of the page. This will not show up in "View Page Source" view, however. Why? Because this modifies the DOM -- the Dynamic Object Model.
To see this new element, you'll either need to look at the rendered output (what the user/you sees), or open up your browser's DevTools (often <F12>, or right-click -> inspect). In the DevTools, find the "Inspector" tab (or equivalent), then look for your new element in this live view of the DOM.
... same output in php.
In short, you can't. What Ctrl+U / View Page Source shows is the page as it was initially received from the server. This would be the exact content you would see if you were to use a command line tool, like curl or wget:
curl http://url.to.your.com/page
Since you include 'folder_location/sample.php' at the server, this is included in the page before the browser sees it. For your edification, I would consider reading up on the DOM.
Wikipedia
W3
Try this:
$("#rpttable tbody tr").remove();
var content = '' ;
for (i = 0; i < data.length; i++) {
content += "<tr>" ;
for (x in data[i]) {
content += "<td>" + data[i][x] + "</td>" ;
}
content += "</tr>" ;
}
$("#rpttable tbody").html(content) ;
Updated
I am using Google Chrome too. Please try the below code, and check the inspect element each time you add a new row. You can see the html in the Inspect Element changing!
function AppendNewRowToTable() {
var trLen = $("table tbody tr").length ;
var content = "" ;
content += "<tr>" ;
for (i = 0; i < 5; i++) {
content += "<td>" + trLen + "-" + i + "</td>" ;
}
content += "</tr>" ;
$("table tbody").append(content) ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Add new Row
<br />
<table>
<thead>
<tr>
<th>Title 01</th>
<th>Title 02</th>
<th>Title 03</th>
<th>Title 04</th>
<th>Title 05</th>
</tr>
</thead>
<tbody></tbody>
</table>
It seems your intent is to append extra rows to the table in your html response generated from your PHP script.
For that you don't need to clear all existing rows.
$("#rpttable tr").remove();
Build an array of rows and append once to your table body.
var $tbody = $('#rptbody');
var tableRowAdditions = [];
for (var i = 0; i < data.length; i++) {
var $tr = $("<tr></tr>");
for (var x in data[i]) {
var $td = $("<td></td>");
$td.html(data[i][x]);
$tr.append(td);
}
tableRowAdditions.push(tr);
}
$tbody.append(tableRowAdditions);
For a "pure" JavaScript approach, you can create elements using the createElement Web API
For example:
A paragraph with text "Hello" would be
var container = document.getElementById('rptbody');
var hello = document.createTextNode('Hello');
var helloParagraph = Document.createElement('p');
// Add text to paragraph
helloParagraph.appendChild(hello);
// Append to container
container.appendChild(helloParagraph);
The best way to create elements using jQuery is to use the following format:
// Create the TR and TD elements as jQuery objects.
var tr = $("<tr></tr>", {
"id":"tr1",
"class":"tr"
});
var td = $("<td></td>", {
"id":"td1",
"class":"td",
"text": "Sample Data",
click: function() {
// optional: Function to attach a click event on the object
alert("Clicked!");
}
});
// Attach the element to the document by appending it
// inside rptbody (after all existing content inside #rptbody)
$("#rptbody").append(tr);
tr.append(td);
// OR, Attach the element to the document by prepending it
// inside rptbody (before all existing content in #rptbody)
$("#rptbody").prepend(tr);
tr.append(td);
// OR, Attach the element to the document by completely replacing the content of #rptbody
$("#rptbody").html(tr);
tr.append(td);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
</tbody>
</table>
How do I append two tags to the same row? Current this is only creating a td tag not putting the a tag inside of it. This is the desired result.
Desired:
<td class="link-text">Click Here</td>
Current code:
var newRow = $('<tr>').attr('id', keyID);
newRow.append($('<td class="link-text">').text(artist_name));
newRow.append($('<td><a class="link-text" style="padding:5px;" target="_blank">').attr("href", link).text(link));
newRow.append($('<td class="link-text">').text(email));
To get your desired result:
<td class="link-text>Click Here</td>
You can do something like this:
First create your td, then append your a to that td, and then append that td to your tr
var newRow = $('<tr>').attr('id', 51);
var newTd = $('<td class="link-text">');
newTd.append($('<a style="padding:5px;" target="_blank"></a>').attr("href", 'google.com').text('Click here'));
newRow.append(newTd);
$('.container').append(newRow);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
you are adding href attribute to the td element not the a element, so first create a td element then add a element inside this and then add the td to to tr element. use like this
var newRow = $('<tr>').attr('id', keyID);
newRow.append($('<td class="link-text">').text(artist_name));
var newTd = $('<td class="link-text">');
newTd.append($('<a style="padding:5px;" target="_blank"></a>').attr("href", link).text('Click Here'));
newRow.append(newTd);
newRow.append($('<td class="link-text">').text(email));
$('table tbody').append(newRow);
Check this out
$(document).ready(function(){
$("table tbody tr:first").append('<td class="link-text">Click Here</td>');
});
I am trying to following the example here and create a popover table row. When I just copy the code it works like a charm. But in the table where I want the popup to work it fails.
I have the following JavaScript code (same as Fiddle):
// Popover
var options = { placement: 'bottom', trigger: 'manual', html: true, title: 'This row' };
function createPopover(element, args) {
var href = $(element).data('popover-url'), txt = $(element).data('popover-content');
var html = '<p>Challenge: Can you click the link in a popover?</p><p><a href="' + href
+ '">' + txt + '</a></p>';
$(element).data('content', html).popover(args);
}
function popoverPlacementBottom() {
createPopover($(this), options);
}
$('.row').each(popoverPlacementBottom);
var insidePopover = false;
function attachEvents(tr) {
$('.popover').on('mouseenter', function () {
insidePopover = true;
});
$('.popover').on('mouseleave', function () {
insidePopover = false;
$(tr).popover('hide');
});
}
$('table').on('mouseenter', 'tr', function () {
var tr = $(this);
setTimeout(function () {
if (!insidePopover) {
$(tr).popover('show');
attachEvents(tr);
}
}, 200);
});
$('table').on('mouseleave', 'tr', function () {
var tr = $(this);
setTimeout(function () {
if (!insidePopover) $(tr).popover('hide');
}, 200);
});
and try to have popovers on this table:
<table class="table table-condensed scrollable popup">
<thead>
<tbody id="logEvents">
<tr class="row" data-popover-url="#url_for_row_1" data-popover-content="line 1" data-
original-title="" title="">
<td class="col-md-1">18:27</td>
<td class="col-md-5">InfoService</td>
<td>Blabla...</td>
</tr>
</tbody>
</table>
This however, does not work. While it does work at the table underneath which looks like this:
<table class="popup">
<tbody>
<tr class="row" data-popover-url="#url_for_row_1" data-popover-content="line 1" data-original- title="" title="">
<td>the first line</td>
</tr>
</tbody>
</table>
Why does it not work at the table where it should work? I hope someone can help me out.
/EDIT Okay I made my own Fiddle HERE.
Strangely enough the code works in the Fiddle. But on my webpage it does not. The only difference with the Fiddle is that the tr rows are dynamically generated everytime an event happens by the function:
return "<tr " + trClass + " data-popover-content='line 1' data-popover-url='#url_for_row_1'>"
+ "<td class='col-md-1'>" + time + "</td>"
+ "<td class='col-md-5'>" + item.Source + "</td>"
+ "<td>" + item.DescriptionShort + "</td>"
// + "<td class='col-md-6'>" + "<a id='pop' data-content='test' data-
toggle='popover'>" + item.DescriptionShort + "</a></td>"
+ "</tr>";
Could this have anything to do with it? (e.g., that the id's and classes come after the document-ready? And that I need to reassign the classes every time a new event happens? And if so, how?
Okay the problem was in the generated code! The <tr>'s were generated everytime an event happened and so I should not assign the popover event only at document ready, but also everytime a new row was created.
I put the popover() function in his own pop namespace, and added the pop.popOver() after the new event made a new row. Looked as follows:
this.addData = function (item) {
var container = $(this.cId);
container.append(this.getEventHtml(item));
pop.popOver();
}
Now the popups show! YEAH! Thanks to Suman Bogati for his help.
I have a html table
<TABLE id="dlStdFeature" Width="300" Runat="server" CellSpacing="0" CellPadding="0">
<TR>
<TD id="stdfeaturetd" vAlign="top" width="350" runat="server"></TD>
</TR>
</TABLE>
I am dynamically adding values to it as :
function AddToTable(tblID, value)
{
var $jAdd = jQuery.noConflict();
var row= $jAdd("<tr/>").attr("className","lineHeight");
var cell = $jAdd("<td/>").attr({"align" : "center","width" : "3%"});
var cell1 = $jAdd("<td/>").html("<b>* </b>" + value);
row.append(cell);
row.append(cell1);
$jAdd(tblID).append(row);
}
Now I want a function to remove a row from this table if the value matches..as
function RemoveFromTable(tblID, VALUE)
{
If(row value = VALUE)
{
remove this row
}
}
Here VALUE is TEXT ..which needs to be matched..If exists need to remove that row,,
try this
function RemoveFromTable(tblID, VALUE){
$("#"+tblID).find("td:contains('"+VALUE+"')").closest('tr').remove();
}
hope it will work
Try like this
function RemoveFromTable(tblID, VALUE)
{
If(row value = VALUE)
{
$("TR[id="+VALUE+"]").hide(); //Assumes that VALUE is the id of tr which you want to remove it
}
}
You can also .remove() like
$("TR[id="+VALUE+"]").remove();
I highly recommend using a ViewModel in your case. So you can dynamically bind your data to a table and conditionally format it to whatever you like. Take a look at Knockout.js: http://knockoutjs.com/
function RemoveFromTable(tblID, VALUE){
$(tblID).find('td').filter(function(){
return $.trim($(this).text()) === VALUE;
}).closest('tr').remove();
}
Remove row from HTML table that doesn't contains specific text or string using jquery.
Note: If there are only two column in HTML table, we can use "last-child" attribute to find.
*$(document).ready(function(){
$("#tabledata tbody .mainTR").each(function(){
var lastTD = $(this).find("td:last-child");
var lastTdText = lastTD.text().trim();
if(!lastTdText.includes("DrivePilot")){
$(this).remove();
}
});
});
Note: If there are more than two column in HTML table, we can use "nth-child(2)" attribute to find.
Passing column index with "nth-child(column index)"
$(document).ready(function(){
$("#tabledata tbody .mainTR").each(function(){
var lastTD = $(this).find("td:nth-child(2)");
var lastTdText = lastTD.text().trim();
if(!lastTdText.includes("DrivePilot")){
$(this).remove();
}
});
});
Note: "DrivePilot" is nothing but text or string