How to pass html element(table) dynamically to angular directive? - javascript

I have html tables which are rendered using ng-repeat, i have to export data of that tables into csv file, I found one directive which does it, it works well for one table and did not works properly when there are multiple tables which are using same directive. When i click on export button then the last processed html table is exported not the required one. Bellow i given my HTML code. Here is PLUNKER
<label for="state" class="control-label col-sm-2"><span class="tag">Select territory:</span></label>
<div class="col-sm-2">
<select ng-model="rtype" ng-options="reportName for (reportName, reportType) in reportTypeOptions" class="form-control" id="rtype"></select>
</div>
</div>
<div class="col-sm-9 " style="margin-top: 30px;" ng-show="userLocations.stateWise">
<a ng-click='csv.generate($event, filename() + ".csv", t1)' href=''><button class="btn btn-default export-btn">Export</button></a>
<table id="t1" ng-table="tableParams1" show-filter="false" class="table table-condensed table-bordered table-striped" ng-show="rtype === 'state'" export-csv='csv'>
<tr ng-repeat="(key, value) in userLocations.stateWise">
<td data-title="'Sr No.'" style="width:3%;">{{ $index + 1 }}</td>
<td data-title="'State'" style="width:5%;">{{ key }} </td>
<td data-title="'Total Users'" style="width:7%;">{{ value }} </td>
</tr>
</table>
<table id="t2" ng-table="tableParams2" show-filter="false" class="table table-condensed table-bordered table-striped" ng-show="rtype === 'dist'" export-csv='csv'>
<tr ng-repeat="(key, value) in userLocations.districtWise">
<td data-title="'Sr No.'" style="width:3%;" style="width:3%;">{{ $index + 1 }}</td>
<td data-title="'State'" style="width:5%;">{{ value.userLocation.state }} </td>
<td data-title="'District'" style="width:7%;">{{ value.userLocation.district }} </td>
<td data-title="'Total Users'" style="width:7%;">{{ value.totalUsers }} </td>
</tr>
</table>
<table id="t3" ng-table="tableParams3" show-filter="false" class="table table-condensed table-bordered table-striped" ng-show="rtype === 'pin'" export-csv='csv'>
<tr ng-repeat="(key, value) in userLocations.pincodeWise">
<td data-title="'Sr No.'" style="width:3%;" style="width:3%;">{{ $index + 1 }}</td>
<td data-title="'State'" style="width:5%;">{{ value.userLocation.state }} </td>
<td data-title="'District'" style="width:7%;">{{ value.userLocation.district }} </td>
<td data-title="'Pincode'" style="width:7%;">{{ value.userLocation.pincode }} </td>
<td data-title="'Total Users'" style="width:7%;">{{ value.totalUsers }} </td>
</tr>
</table>
</div>
` // Angular directive code toexport table
app.directive('exportCsv', ['$parse', '$timeout', 'ngTableEventsChannel', function ($parse, $timeout, ngTableEventsChannel) {
var delimiter = ',';
var header = 'data:text/csv;charset=UTF-8,';
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
var data = '';
if (attrs.delimiter) { delimiter = attrs.delimiter; }
function stringify(str) {
return '"' +
str.replace(/^\s\s*/, '').replace(/\s*\s$/, '')
.replace(/"/g,'""') + '"';
}
function parseTable() {
data = '';
var rows = element.find('tr');
angular.forEach(rows, function(row, i) {
var tr = angular.element(row),
tds = tr.find('th'),
rowData = '';
if (tr.hasClass('ng-table-filters')) {
return;
}
if (tds.length === 0) {
tds = tr.find('td');
}
if (i !== 1) {
angular.forEach(tds, function(td) {
rowData += stringify(angular.element(td).text()) + Array.apply(null, Array(td.colSpan)).map(function () { return delimiter; }).join('');
});
rowData = rowData.slice(0, rowData.length - 1);
}
data += rowData + '\n';
});
data = 'sep=' + delimiter + '\n' + data;
}
function download(dataUri, filename, scope) {
var link = document.createElement('a');
link.style.display = 'none';
link.href = dataUri;
link.download = filename;
link.target = '_blank';
$timeout(function () {
try {
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
catch(err) {
if (scope.logError) {
scope.logError('NG Table Export Error saving file on client.');
}
throw(err);
}
}, 0, false);
}
// csv var for calling its method
var csv = {
generate: function(event, filename, table) {
var isNgTable = attrs.ngTable,
table = table || scope.$parent.tableParams,
settings = table ? table.settings() : {},
cnt = table ? table.count() : {},
total = table ? settings.total : {};
if (isNgTable && cnt < total) {
var $off = ngTableEventsChannel.onAfterReloadData(function () {
$off();
$timeout(function () {
parseTable();
table.count(cnt);
table.reload();
download(header + encodeURIComponent(data), filename, scope);
}, 1000, false);
});
table.count(Infinity);
table.reload();
} else {
parseTable();
download(header + encodeURIComponent(data), filename);
}
}
};
$parse(attrs.exportCsv).assign(scope.$parent, csv);
}
};
}]);`
How to give element to directive if element occurs more than once.

Related

Search still works after deleting a user + cells keep being created without an input

been working on some basic contacts app and got stuck in two places. Cells keep being created in the table even if there's no input (I've tried if statements) + after deleting a contact I can still search for it. How to remove it from the database? Is it possible to make the create button appear after all the fields have input in it? How can I remove the elements from db array after deleting the cells?
let db = [];
let contact = {};
// ADD CONTACT
$(document).ready(function() {
$("#create-contact").on("click", function(event) {
event.preventDefault();
contact.firstName = $('#name').val();
contact.surname = $('#surname').val();
contact.phone = $("#phone").val();
contact.address = $("#address").val();
let row = document.createElement("tr");
$("table").append(row);
let cell1 = document.createElement("td");
let cell2 = document.createElement("td");
let cell3 = document.createElement("td");
let cell4 = document.createElement("td");
let dltBtn = document.createElement("button");
/* ^ https://stackoverflow.com/questions/268490/jquery-document-createelement-equivalent
Fastest method */
$(dltBtn).text("X")
.css("width", "8.5rem")
.css("color", "white")
.css("background-color", "black")
.attr("class", "dltBtn");
$(cell1).html(contact.firstName);
$(cell2).html(contact.surname);
$(cell3).html(contact.phone);
$(cell4).html(contact.address);
row.append(cell1, cell2, cell3, cell4,dltBtn);
db.push(contact.firstName, contact.surname, contact.phone, contact.address);
console.log(db);
$('.dltBtn').on('click', function(event) {
event.preventDefault();
row.remove(dltBtn)
.deleteCell();
});
});
// SEARCH
function search(name) {
for (i = 0; i < db.length; i++) {
if (!isNaN(name) && db[i] === name) {
return db[i-2] + " " + db[i-1] + " " + db[i] + " " + db[i+1];
}
if (db[i].toUpperCase() === name.toUpperCase()) {
return db[i] + " " + db[i+1] + " " + db[i+2] + " " + db[i+3];
}
$("#found").text("User not found!");
}
};
$('.searchbutton').on('click', function(event) {
event.preventDefault();
var findUserName = $('#query').val();
var userFound = search(findUserName);
$("#found").text(userFound);
console.log(db);
});
});
This example might be more complex than you are needing. Consider creating a db Object with built in functions.
$(function() {
var db = {
content: [],
headers: [
"First Name",
"Last Name",
"Phone",
"Address",
" "
],
tableRef: null,
insert: function(row) {
this.content.push(row);
this._drawTable();
},
delete: function(row_id) {
this.content.splice(row_id, 1);
this._drawTable();
},
search: function(term) {
if (term == undefined || term == "") {
return false;
}
var table = $(this.tableRef);
$("tbody tr", table).hide().each(function(i, row) {
if ($("td:eq(0)", row).text().toLowerCase().indexOf(term.toLowerCase()) >= 0) {
$(row).show();
}
});
},
_getContent: function(id) {
this.tableRef = id;
var table = $(id);
var headers = [];
var rows = [];
$("thead th", table).each(function(i, h) {
headers.push($(h).text());
});
this.headers = headers;
$("tbody tr", table).each(function(i, r) {
rows.push({
firstName: $("td:eq(0)", r).text(),
surName: $("td:eq(1)", r).text(),
phone: $("td:eq(2)", r).text(),
address: $("td:eq(3)", r).text()
});
});
this.content = rows;
console.log("Content collected from " + this.tableRef, this.content.length + " rows.");
},
_drawTable: function() {
var table;
if ($(this.tableRef).length) {
table = $(this.tableRef);
$("tbody tr", table).remove();
} else {
this.tableRef = "#contacts";
table = $("<table>", {
id: "contacts"
}).appendTo("body");
$("<thead>").appendTo(table);
$("<tr>").appendTo($("thead", table));
$.each(this.headers, function(i, h) {
$("<th>").html(h).appentTo($("thead > tr", table));
});
$("<tbody>").appendTo(table);
}
var row;
$.each(this.content, function(i, r) {
row = $("<tr>").appendTo($("tbody", table));
$.each(r, function(j, c) {
$("<td>").html(c).appendTo(row);
});
});
console.log("Table Drawn", this.content.length + " rows");
}
};
db._getContent("#contacts");
$("#contacts").on("click", ".dlt-btn", function(e) {
var rId = $(this).closest("tr").index();
if (confirm("Are you sure you wish to delete this entry?")) {
db.delete(rId);
}
});
$("#add_contact_form").submit(function(event) {
event.preventDefault();
var contact = {
firstName: $("input:eq(0)", this).val(),
surName: $("input:eq(1)", this).val(),
phone: $("input:eq(2)", this).val(),
address: $("input:eq(3)", this).val()
};
db.insert(contact);
this.reset();
});
$("#search_contacts").on("input", "input", function() {
if ($(this).val().length >= 1) {
db.search($(this).val());
} else {
$(db.tableRef).find("tbody tr").show();
}
});
});
#add_contact td,
#add_contact input {
width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="search_contacts">
Search: <input type="text">
</form>
<table id="contacts" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>Homer</td>
<td>Simpson</td>
<td>(939)-555-0113</td>
<td>742 Evergreen Terrace</td>
<td><button class="dlt-btn">X</button></td>
</tr>
<tr>
<td>Marge</td>
<td>Simpson</td>
<td>(939)-555-0113</td>
<td>742 Evergreen Terrace</td>
<td><button class="dlt-btn">X</button></td>
</tr>
<tr>
<td>Bart</td>
<td>Simpson</td>
<td>(939)-555-0113</td>
<td>742 Evergreen Terrace</td>
<td><button class="dlt-btn">X</button></td>
</tr>
<tr>
<td>Lisa</td>
<td>Simpson</td>
<td>(939)-555-0113</td>
<td>742 Evergreen Terrace</td>
<td><button class="dlt-btn">X</button></td>
</tr>
<tr>
<td>Maggie</td>
<td>Simpson</td>
<td>(939)-555-0113</td>
<td>742 Evergreen Terrace</td>
<td><button class="dlt-btn">X</button></td>
</tr>
</tbody>
</table>
<form id="add_contact_form">
<table id="add_contact" width="100%">
<tbody>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td width="30px"> </td>
</tr>
</tbody>
</table>
<button type="submit" id="create-contact">Create Contact</button>
</form>
There are lots of ways to manage Arrays. Please see:
https://www.w3schools.com/jsref/jsref_push.asp
https://www.w3schools.com/jsref/jsref_splice.asp
https://www.w3schools.com/jsref/jsref_indexof_array.asp
Once you adjust the Array you need to either redraw the table or perform the same function to the Table element.
Searching, or in this case, filtering, can be done in a lot of ways too. This is a pretty basic example. You can look at other options if you like.

Get checkbox values with different class name in the same div id - jquery mvc

I am trying to get the values of checkboxes which are in the same divid but have different class name.
<tr>
<td colspan="4" align="center">
<div id="divEntities" style="width:100%;height:150px;overflow-y:scroll;align:center;">
<table cellspacing="2" cellpadding="2" width="95%" align="center" border="1">
#{
var i = 0;
while (i < Model.CompanyMaster.Count)
{
<tr>
<td style="width:50%" hidden="hidden"><input type="checkbox" class="EntityCheck" id="chkCompanyId" /> #Model.CompanyMaster[i].COMPANYID</td>
#if ((i + 1) < Model.CompanyMaster.Count)
{
<td><input type="checkbox" class="EntityCheck" /> #Model.CompanyMaster[i + 1].COMPANY_NAME</td>
<td><input type="checkbox" class="CurrentYear" /> #DateTime.Now.Year </td>
<td><input type="checkbox" class="PreviousYear" /> #DateTime.Now.AddYears(-1).Year </td>
<td><input type="checkbox" class="LastYear" /> #DateTime.Now.AddYears(-2).Year </td>
}
else
{
<td></td>
}
</tr>
i = i + 1;
}
}
</table>
</div>
</td>
</tr>
With above code, I am able to populate data in a table with multiple checkboxes, but unable to get the value of the checkbox where the class name is something other than EntityCheck. Below is my jQuery function:
function GetSelectedEntities() {
var entities = "";
$("#divEntities").find('td').each(function (i, el) {
var checkbox = $(this).find('input.EntityCheck');
//var check1 = $(this).find('CurrentYear');
//var check2 = $(this).find('PreviousYear');
//var check3 = $(this).find('LastYear');
var check1 = $('.CurrentYear').val();
var check2 = $('.PreviousYear').val();
var check3 = $('.LastYear').val();
if (checkbox != undefined && $(checkbox).length > 0 && $(checkbox).prop('checked') == true) {
var EntityData = jQuery.trim($(this).text());
if (entities == "") {
entities = EntityData;
}
else {
entities = entities + "|" + EntityData;
}
}
});
return entities;
}
jQuery function is invoked on a button click event:
<button style="font:normal 9pt Arial;height:30px;width:100px;border-radius:5px; border:none; background-color:royalblue; color:white" id="btnAdd" onclick="GetSelectedEntities(event);">
Add
</button>
I tried by giving the same class name to all the checkboxes but the problem was that I was able to get the values of the year checkbox, even if the CompanyName was not selected. I need the year values only if the CompanyName checkbox is checked and it's corresponding years. I also tried by giving the id='' to the year checkbox, but could not get the values.
I am unable to figure where I am going wrong. What is that I need to change in my jQuery to get the expected result?
Something like this would work:
$('#btnAdd').on('click', function(){
var checked = $('table').find('input:checked');
checked.each(function(){
alert($(this).closest('td').text());
//do your stuff here..
});
});
Se working fiddle: https://jsfiddle.net/c8n4rLjy/
I had to make changes to get the desired solution. Please find the solution below:
<tr>
<td colspan="4" align="center">
<div id="divEntities" style="width:100%;height:150px;overflow-y:scroll;align:center;">
<table cellspacing="2" cellpadding="2" width="95%" align="center" border="1">
#{
var i = 0;
while (i < Model.CompanyMaster.Count)
{
<tr>
<td style="width:50%" hidden="hidden"><input type="checkbox" class="EntityCheck" id="chkCompanyId" /> #Model.CompanyMaster[i].COMPANYID</td>
#if ((i + 1) < Model.CompanyMaster.Count)
{
<td><input type="checkbox" class="EntityCheck" /> #Model.CompanyMaster[i + 1].COMPANY_NAME</td>
<td><input type="checkbox" class="chkYear" /> #DateTime.Now.Year </td>
<td><input type="checkbox" class="chkYear" /> #DateTime.Now.AddYears(-1).Year </td>
<td><input type="checkbox" class="chkYear" /> #DateTime.Now.AddYears(-2).Year </td>
}
else
{
<td></td>
}
</tr>
i = i + 1;
}
}
</table>
</div>
</td>
</tr>
jQuery:
function GetSelectedEntities() {
var entities = "";
var CompanySelected = false;
var counter = 0;
$("#divEntities").find('td').each(function (i, el) {
counter = counter + 1
var checkbox = $(this).find('input.EntityCheck');
var checkboxyear = $(this).find('input.chkYear');
if (counter == 2) {
if (checkbox != undefined) {
if ($(checkbox).prop('checked') == true) {
CompanySelected = true;
var EntityData = jQuery.trim($(this).text());
if (entities == "") {
entities = EntityData;
}
else {
entities = entities + "-" + EntityData;
}
}
else {
CompanySelected = false;
}
}
}
if (counter > 2) {
if (CompanySelected == true) {
if (checkboxyear != undefined) {
if ($(checkboxyear).prop('checked') == true) {
var EntityData = jQuery.trim($(this).text());
entities = entities + "|" + EntityData;
}
}
}
}
if(counter == 5)
{
counter = 0;
}
});
return entities;
}

using TableHTMLExport, how can i tell it to ignore certain divs and spans?

I am using
https://github.com/FuriosoJack/TableHTMLExport
I've got a rather complicated table with lots of hidden elements and I wanted a way to export this table using the said plugin. It works fine actually except it's also exporting all the hidden elements (style = display: hidden)
I've gone through the docs and I can't find the options for this.
All I could come up with is this:
$("#myTable").tableHTMLExport({
type: 'csv',
htmlContent: false,
filename: filename_csv,
ignoreColumns: '.export_ignore_col',
ignoreRows: '.export_ignore_row'
});
Alternative way :
You can read there documentation there is codepen link you can edit this code to achieve above . In below code i have made changes inside toCsv function .First i have check if the td or th has children and if the length > 0 then i have loop through childrens node and have check if they are visible or not depending on this i have appended value inside output variable.
Demo Code(with dummy datas) :
(function($) {
$.fn.extend({
tableHTMLExport: function(options) {
var defaults = {
separator: ',',
newline: '\r\n',
ignoreColumns: '',
ignoreRows: '',
type: 'csv',
htmlContent: false,
consoleLog: false,
trimContent: true,
quoteFields: true,
filename: 'tableHTMLExport.csv',
utf8BOM: true,
charSet: 'utf-8',
orientation: 'p' //only when exported to *pdf* "portrait" or "landscape" (or shortcuts "p" or "l")
};
var options = $.extend(defaults, options);
function quote(text) {
return '"' + text.replace('"', '""') + '"';
}
function parseString(data) {
if (defaults.htmlContent) {
content_data = data.html().trim();
} else {
content_data = data.text().trim();
}
return content_data;
}
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/csv;charset=' + options.charSet + ',' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
/**
* Convierte la tabla enviada a csv o texto
* #param table
* #returns {string}
*/
function toCsv(table) {
var output = "";
if (options.utf8BOM === true) {
output += '\ufeff';
}
var rows = table.find('tr').not(options.ignoreRows);
var numCols = rows.first().find("td,th").not(options.ignoreColumns).length;
rows.each(function() {
$(this).find("td,th").not(options.ignoreColumns)
.each(function(i, col) {
var column = $(col);
//check if td or th has children .ie. : any div or span..etc
if ($(col).children().length > 0) {
//loop through it
$(col).children().each(function() {
//check if the element is visible(not hidden)
if ($(this).is(':visible')) {
//append them inside output variable
output += $(this).text();
}
})
} else {
// Strip whitespaces
var content = options.trimContent ? $.trim(column.text()) : column.text();
output += options.quoteFields ? quote(content) : content;
}
if (i !== numCols - 1) {
output += options.separator;
} else {
output += options.newline;
}
});
});
console.log(" Output >>> " + output)
return output;
}
var el = this;
var dataMe;
if (options.type == 'csv' || options.type == 'txt') {
var table = this.filter('table'); // TODO use $.each
if (table.length <= 0) {
throw new Error('tableHTMLExport must be called on a <table> element')
}
if (table.length > 1) {
throw new Error('converting multiple table elements at once is not supported yet')
}
dataMe = toCsv(table);
if (defaults.consoleLog) {
console.log(dataMe);
}
download(options.filename, dataMe);
}
return this;
}
});
})(jQuery);
$("#tableCompany").tableHTMLExport({
type: 'csv',
filename: 'soemthingss.csv',
ignoreColumns: '.acciones,#primero',
ignoreRows: ''
});
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://unpkg.com/jspdf#1.5.3/dist/jspdf.min.js"></script>
<script src="https://unpkg.com/jspdf-autotable#3.2.3/dist/jspdf.plugin.autotable.js"></script>
<table id="tableCompany">
<thead>
<tr>
<th>Company</th>
<th>Contactt</th>
<th class='acciones'>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td><span>Alfreds Futterkiste </span>
<div style="display:none">cdcdcdcdci</div>
<div>sti</div>
</td>
<td id="primero">Maria Anders</td>
<td class="acciones">Germany</td>
</tr>
<tr>
<td><span>Ernst Handel </span>
<div style="display:none">cdi</div>
<div>soemthinss</div>
</td>
<td>Roland Mendel</td>
<td class="acciones">Austria</td>
</tr>
<tr>
<td><span>Island Trading </span>
<div style="display:none">tr</div>
</td>
<td><span>Helen Bennett </span>
<div style="display:none">tr</div>
<div>twew</div>
</td>
<td>UK</td>
</tr>
</tbody>
</table>

How to show data from a database in my table from my website?

I have a database that I want to access to display my product data, in this case the ItemCode and ItemName.
the connections are all correct and the functional, my problems is the loop and show the data in the table that I have in the html file.
let ctrl = {
showDados: function(r) {
/*dados[3].ItemCode;*/
let dados = JSON.parse(r.responseText);
let cod = dados.ItemCode;
let name = dados.ItemName;
let text = "";
let i;
for (i = 0; i < cod.length; i++) {
text += cod[i] + "<br>";
}
document.getElementById("cod").innerHTML = text;
for (i = 0; i < name.length; i++) {
text += name[i] + "<br>";
}
document.getElementById("name").innerHTML = text;
},
init: function() {
util.ajax(settings.serviceAddress + "OITM", ctrl.showDados);
}
};
$(document).ready(function() {
ctrl.init();
});
<div class="container">
<table class="table table-hover">
<thead>
<tr>
<th>Código</th>
<th>Nome</th>
</tr>
</thead>
<tbody>
<tr>
<td id="cod">FSE0204</td>
<td id="name">25130101_Loc.Finaneira - BCP- CT 400105814</td>
</tr>
<tr>
<td>FSE0205</td>
<td>25130201_Loc.Finaneira - Totta- CT 195649</td>
</tr>
</tbody>
</table>
</div>

Conversion of javascript to jquery (getelementbyid, tagname, innertext, innerhtml)

I have some code written in javascript n when I am trying to convert in jQuery I am getting error.
var holder = document.getElementById('filedetails')
, rows = holder.getElementsByTagName('tr')
setSuccess = function(filename) {
if (holder != null) {
for (i = 0, j = rows.length; i < j; ++i) {
cells = rows[i].getElementsByTagName('td');
if (cells[0].innerText == filename && cells[3].innerText != "error!") {
cells[3].innerHTML = "<a href='#' class='file-delete ss-delete no-click'></a>";
}
}
}
}
I tried
var holder = $('#filedetails"),
rows = $('#filedetails tr")
I am not sure what to do with innertext and innerhtml.
<div data-behavior="delete-process" id="holder">
<table>
<thead>
<tr>
<th class="medium-5">Name</th>
<th class="medium-3">Size</th>
<th class="medium-3">Type</th>
<th class="medium-1"></th>
</tr>
</thead>
<tbody id="filedetails">
<tr data-filesize="1.4" data-filename="Sample Image.jpg">
<td><strong>Sample_Image</strong></td>
<td class="nodesize">1.4 MB</td>
<td>JPG</td>
<td class="file-loading"></td></tr>
</tbody>
</table>
<div class="margin bottom large text-center drag-desc">drag and drop files here.</div>
</div>
Here is a "jqueryized" version of your code
var holder = $('#filedetails'),
rows = holder.find('tr');
var setSuccess = function(filename) {
rows.each(function() {
var cells = $(this).find('td');
if (cells.eq(0).text() == filename && cells.eq(3).text() != "error!") {
cells.eq(3).html("<a href='#' class='file-delete ss-delete no-click'></a>");
}
});
};
setSuccess("Sample_Image");
Alternate that just uses the rows:
var rows = $('#filedetails').find('tr');
var setSuccess = function(filename,useme) {
useme.each(function() {
var cells = $(this).find('td');
if (cells.eq(0).text() == filename && cells.eq(3).text() != "error!") {
cells.eq(3).html("<a href='#' class='file-delete ss-delete no-click'>freebeer</a>");
}
});
};
setSuccess("Sample_Image", rows);
To NOT use a positional table element, use a class and filter by that within the TD cells as here: This assumes one use of a class per row.
var rows = $('#filedetails').find('tr');
var setSuccess = function(filename, useme) {
useme.each(function() {
var cells = $(this).find('td');
if (cells.filter('.file-name').text() == filename
&& cells.filter('.file-loading').text() != "error!") {
cells.filter('.file-loading')
.html("<a href='#' class='file-delete ss-delete no-click'>noclick</a>");
}
});
};
setSuccess("Sample_Image", rows);
Fiddl https://jsfiddle.net/MarkSchultheiss/0fx2jms7/2/
Check the following code snippet
$(document).ready(function(){
var holder = $("#filedetails")
, rows = holder.find('tr');
var rowsLength=rows.Length;
var setSuccess = function(filename) {
if (holder != null) {
var j=rows.length;
for (var i=0; i < j; ++i) {
var cells = $(rows[i]).find('td');
var filename=$('.filename');
var file=$('.file');
if (filename.text() == filename && file.text() != "error!")
{
var aElement=$("<a/>");
aElement.href="#";
aElement.class="file-delete ss-delete no-click";
file.html(aElement);
}
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-behavior="delete-process" id="holder">
<table>
<thead>
<tr>
<th class="medium-5">Name</th>
<th class="medium-3">Size</th>
<th class="medium-3">Type</th>
<th class="medium-1"></th>
</tr>
</thead>
<tbody id="filedetails">
<tr data-filesize="1.4" data-filename="Sample Image.jpg">
<td class="filename"><strong>Sample_Image</strong></td>
<td class="nodesize">1.4 MB</td>
<td>JPG</td>
<td class="file-loading file"></td></tr>
</tbody>
</table>
<div class="margin bottom large text-center drag-desc">drag and drop files here.</div>
</div>
Hope this helps

Categories

Resources