Set Link in table cell with jQuery - javascript

I have a table with three td´s. In the third td I´d like to dynamically set a link in a with data from other two td cells.
I know, how to change the link, but every row get the link from the first row. Maybe a very simple solution, but I´m a little helpless
My Code so far:
HTML:
<table id="table">
<tbody>
<tr>
<td class="one">11</td>
<td class="two">12</td>
<td class="three"><a href='#'>13</a></td>
</tr>
<tr>
<td class="one">21</td>
<td class="two">22</td>
<td class="three">23</td>
</tr>
</tbody>
</table>
Script:
$(document).ready(function () {
var row = $('#table .three a').closest('tr');
var td = row.find('td');
var id1 = td.eq(0).text();
var id2 = td.eq(1).text();
$('#table .three a').attr("href", "test.html?" + id1 + "-" + id2);
});
Fiddle

You can use this:
$('#table .three a').each(function () {
var id1 = $(this).closest('tr').find('td:eq(0)').text();
var id2 = $(this).closest('tr').find('td:eq(1)').text();
$(this).prop("href", "test.html?" + id1 + "-" + id2);
});
jsFiddle example

change your javascript to this
$(document).ready(function () {
$('#table .three a').each(function(){
var row = $(this).closest('tr');
var td = row.find('td');
var id1 = td.eq(0).text();
var id2 = td.eq(1).text();
$(this).attr("href", "test.html?" + id1 + "-" + id2);
})
});

You need to use .each()
$('#table .three a').each(function (index) {
var row = $(this).closest('tr');
var td = row.find('td');
var id1 = td.eq(0).text();
var id2 = td.eq(1).text();
$(this).attr("href", "test.html?" + id1 + "-" + id2);
});
DEMO

Related

adding row and then deleting causes duplicate rows

So when I add new rows each row is given an id that increments according the number of rows already added. if I add three rows and then delete the second row, then add another row, now the new row has an id the same as the old third row.
is there an easier way to do this or a loop that i can perform to check for an existing number.
$('body').delegate('.remove', 'click', function() {
$(this).parent().parent().remove();
});
function addnewrow() {
var n = ($('.detail tr').length - 0) + 1;
var tr = '<tr>' +
'<td>' + n + '</td>' +
'<td><select id="drop' + n + '" class="select-service" name="prodService[]"> <
option value = "" > -Choose Service - < /option></select > < /td>'+
'<td id="desc' + n + '"></td>' +
'<td>Delete</td>' +
'</tr>';
Try this way...Put counter outside of the function.
$('body').on("click", '.remove', function() {
$(this).closest("tr").remove();
});
var n = 1;
$('body').on('click', '.add-new-row', function() {
var $tr = $("<tr />");
var $td1 = $("<td />").text(n).appendTo($tr);
var $td2 = $("<td />").append("<select id='drop" + n + "' class='select-service' name='prodService[]' />").appendTo($tr);
var $td3 = $("<td id='desc" + n + "' />").appendTo($tr);
var $td4 = $("<td />").append("<a href='#' class='remove'>Delete</a>").appendTo($tr);
$("table").append($tr);
n++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add-new-row">Add New Row</button>
<table></table>
Using jQuery is nice because you can avoid writing these giant element strings, so I've gone ahead and rewritten your addnewrow() function to (hopefully) make it slightly cleaner.
As far as determining the IDs, while I believe what talg123 suggested in the comments would be fine - storing a global variable that just increases by 1 each time you add a new row - I personally try to avoid polluting the global scope where I can.
You can use this line to find the last drop id, and remove the "drop" text from it so you're just left with a number.
$("tr select").last().attr("id").replace("drop", "");
Unfortunately, this will break if there are no rows becuase it won't be able to find any select elements. So, first we have to check if they exist:
+$("tr select").length ? (exists) : (does not exist)
If it doesn't exist, we'll just use 1.
Put that all together, and you've got:
//If select exists Get last ID and remove "drop" from it, and add 1 Else, 1
$("tr select").length ? 1 + +$("tr select").last().attr("id").replace("drop", "") : 1;
$('body').on("click", '.remove', function() {
$(this).closest("tr").remove();
});
$('body').on('click', '.add-new-row', function() {
var nextId = $("tr select").length ? 1 + +$("tr select").last().attr("id").replace("drop", "") : 1;
//Create a new select list
var $selectList = $("<select id='drop" + nextId + "' class='select-service' name='prodService[]' />");
$selectList.append("<option> -Select Service- </option"); //Append option 1
$selectList.append("<option> Another example </option"); //Append option 2
var $tr = $("<tr />"); //Create a new table row
var $td1 = $("<td />").text(nextId).appendTo($tr); //Create first cell. Set text to nextId. Add it to the row.
var $td2 = $("<td />").append($selectList).appendTo($tr); //Create second cell. Add our select list to it. Add it to the row.
var $td3 = $("<td id='desc" + nextId + "' />").appendTo($tr); //Create third cell. Set its id to 'desc{nextId}'. Add it to the row.
var $td4 = $("<td />").append("<a href='#' class='remove'>Delete</a>").appendTo($tr); //Create fourth cell. Add link to it. Add it to the row.
$("table").append($tr); //Add the row to the table
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add-new-row">Add New Row</button>
<table></table>

Javascript - Getting removed item name from table?

So I have an table. By click of a button, information will be added there, so each item has also X button, which removes them from the list. I've been trying to do that, if you click that X button, then it will output to console the item name which you deleted. How could I do that?
Here's the function
function sitaSeen(img, name, condition, price) {
$('tbody').append("<tr id='itemCart'><td><img src=" + img + "></td><td>" + name + "</td><td>" + condition + "</td><td>$" + price + "</td><td><span>X</span></td></tr>");
Which is called, when item has to be added.
Here's the X button code
$(document).ready(function() {
$('.sweet-container').on('click', 'tr span', function(){
var removedname = $(this).closest('tr').ignore('span').text();
console.log(removedname);
$(this).closest('tr').remove();
});
});
There's also kind of my try, but ofc it wont work.
There is no ignore() method in jQuery so it will throws error in console. So either clone the tr and remove span from cloned object and then get text or get all td which is not contains span and get text.
$(document).ready(function() {
$('.sweet-container').on('click', 'tr span', function(){
var removedname = $(this).closest('tr').clone().remove('span').text();
// or
// var removedname = $(this).closest('tr').find('td:not(:has(span))').text();
console.log(removedname);
$(this).closest('tr').remove();
});
});
UPDATE : Since you just want the second column you can simply use :nth-child or :eq() selector(or eq()).
$(document).ready(function() {
$('.sweet-container').on('click', 'tr span', function(){
var removedname = $(this).closest('tr').find('td:nth-child(2)').text();
// or
// $(this).closest('tr').find('td:eq(1)').text();
// or
// $(this).closest('tr').children().eq(1).text();
console.log(removedname);
$(this).closest('tr').remove();
});
});
I think it might be better to use:
```
// better way to get to the tr element
var trElem = $(this).parentNode.parentNode;
```
The parentNode attribute is a better way to access the parent of an element.
The item name is the second td so you can use:
var removedname = $(this).closest('tr').find('td:eq(1)').text();
Because the ID have to be unique I added a new parameter to your function.
function sitaSeen(seq, img, name, condition, price) {
$('tbody').append("<tr id='itemCart" + seq + "'>" +
"<td><img src=" + img + "></td>" +
"<td>" + name + seq + "</td>" +
"<td>" + condition + "</td>" +
"<td>$" + price + "</td>" +
"<td><span>X</span></td>" +
"</tr>");
}
$(function () {
$('#addRow').on('click', function(e) {
var seq = +$(this).attr('data-seq');
$(this).attr('data-seq', seq + 1);
sitaSeen(seq, 'img', 'name', 'condition', 'price');
});
$('.sweet-container').on('click', 'tr span', function(){
var removedname = $(this).closest('tr').find('td:eq(1)').text();
console.log(removedname);
$(this).closest('tr').remove();
});
});
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<div class="sweet-container">
<button id="addRow" data-seq="1">Add Row</button>
<table>
<tbody>
</tbody>
</table>
</div>

how to use javascript or jquery create table fast

I want to create a table by click a button,and i need to save the table to the database .this is the code to create table but i think this is so long,how can i create it fast?
var div = document.createElement("div");
var table1 = document.createElement("table");
var table2 =document.createElement("table");
var thead = document.createElement("thead");
var th1 = document.createElement("th");
var th2 = document.createElement("th");
var th3 = document.createElement("th");
th1.innerHTML="Count";
th2.innerHTML="Date";
th3.innerHTML="Price";
document.body.appendChild(div);
div.appendChild(table1);
div.appendChild(table2);
table2.appendChild(thead);
thead.appendChild(th1);
thead.appendChild(th2);
thead.appendChild(th3);
If the code is too long then I recommend creating an html table structure inside a div that is not displayed. Then when the user clicks the button then you could
Display the table that is hidden.
Clone the table and append it to something (if you expect to create the table multiple times)
Your code would then look like so (cloning wise):
jQuery:
$('#myButton').on('click', function(){
$(document.body).append($('original').clone());
});
Javascript:
document.getElementById('myButton').onclick = function(){
document.body.appendChild(document.getElementById('original').cloneNode());
}
And here is the html table you can have hidden.
<div style="display: none;">
<table id="original">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
</div>
This reduces greatly your javascript code.
If you want to make some enhancement than you can use precompiled template like muchtache.js :
<table>
<tr>
<th> Count </th>
<th> Date </th>
<th> Price </th>
</tr>
{{#jsonObject}}
<tr>
<td>{{Count1}}</td>
<td>{{Date1}}</td>
<td>{{Price1}}</td>
</tr>
{{/jsonObject}}
</table>
in javascript, you can write your javascript jsonobject as :
jsonobject : [{
count1 : 1,
date1 : 12/12/2012,
price1 : 100
},
{
count1 : 2,
date1 : 12/12/2013,
price1 : 200
}
]
for full muchtache example visit Json Object into Mustache.js Table
The following function might help:
function html2dom (html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.removeChild(div.firstChild);
}
Here is how to use it:
document.body.appendChild(html2dom(''
+ '<div>'
+ '<table></table>'
+ '<table>'
+ '<thead>'
+ '<th>Count</th>'
+ '<th>Date</th>'
+ '<th>Price</th>'
+ '</thead>'
+ '</table>'
+ '</div>'
));
Live demo:
document.body.appendChild(html2dom(''
+ '<div>'
+ '<p>Paragraph.</p>'
+ '<ul>'
+ '<li>Item 1.</li>'
+ '<li>Item 2.</li>'
+ '<li>Item 3.</li>'
+ '</ul>'
+ '</div>'
));
function html2dom (html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.removeChild(div.firstChild);
}

How to optimize jquery script (table creation N rows X 56 cols)

Hi I have a jquery scripts that takes table template and adds N rows (N=[1...100]) as clones of first TR. then each cell in each row is populated with some data (not all cells are always filled), each cell has " on clik " event attached, and on cell hover row, cell, coll is highlighted.
The problem i am facing is the optimization of generation (time) and usability (the mouse movemnts aren't smooth)
the code:
HTML template table:
<table id='schedulerview' class='myGrid'>
<colgroup id='col_0'></colgroup>
<colgroup id='col_1'></colgroup>
<colgroup id='col_2'></colgroup>
<colgroup id='col_3'></colgroup>
....
<colgroup id='col_55'></colgroup>
<thead>
<tr>
<th>0</th>
<th>1</th>
<th>2</th>
<th>3</th>
....
<th>51</th>
</tr>
</thead>
<tbody>
<tr id='template' style='display:none'>
<td id='0' HID='W0_Y_I' class='scheddata'>Week 1</td>
.....
<td id='51' HID='W55_Y_I' class='scheddata'>Week 52</td>
</tr>
</tbody>
</table>
CSS :
.litrow { background-color: #eee; }
.litcell { background-color: yellow; }
file codebehind.js
$(document).ready(function () {
//turn on row, cell, column highlight on hover
$("table#schedulerview tbody").on('mouseenter', 'tr', function () {
$(this).addClass('litrow');
});
$("table#schedulerview tbody").on('mouseleave', 'tr', function () {
$(this).removeClass('litrow');
});
$("table#schedulerview tbody").on('mouseenter', 'td', function () {
$(this).addClass('litcell');
$("colgroup").eq($(this).index()).addClass("litrow");
});
$("table#schedulerview tbody").on('mouseleave', 'td', function () {
$(this).removeClass('litcell');
$("colgroup").eq($(this).index()).removeClass("litrow");
});
//function for getting data and create schedule table from template table
getSchedule();
});
getschedule function:
function getSchedule() {
var data = "{userid:'" + userid + "',year:" + year + "}";
$.ajax({
type: "POST",
url: "/Scheduler.aspx/getSchedule",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (ret) {
var areas = JSON.parse(ret.d.Areas);
var schedule = JSON.parse(ret.d.Schedule);
//remove all rows from table that are not template
$('table#schedulerview tr.eventSchedule').remove();
//create row for each element from DB - prepare matrix elementsXWeeks
var $tr = $('#template');
$.each(areas, function (i, x) {
var $clone = $tr.clone();
$clone.css('display', 'block');
$clone.attr('id', 'new_row_' + i);
$clone.addClass('eventSchedule');
$clone.children('td:first').text(x.AreaName);
//for each cell in new row
$clone.children('td.scheddata').each(function () {
var $this = $(this);
var HID = $this.attr("HID").replace('_Y_', '_' + year + '_').replace('_I', '_' + x.IDObszaru);
$this.attr("HID", HID);
});
$tr.before($clone);
});
//fill in the matrix with scheduled data
$.each(schedule, function (i, x) {
$td = $("table#schedulerview td[HID='" + x.HID + "']");
$td.addClass(x.Status);
$td.attr("WeekNum", x.WeekNum);
$td.attr("PlanID", x.Id);
$td.parent().addClass('plannedrow');
});
},
error: function (ret) {
alert(ret.responseText);
}
});
}
The getSchedule() function lasts few seconds, is it possible to optimize it so it would be faster?
CHANGES:
I've tried different approach for row creation:
for (i = 0; i < areas.length; i++) {
$lasttr = $("table#schedulerview tbody").append("<tr id='new_row_" + i + "' class='eventSchedule' ></tr>");
$lasttr = $("table#schedulerview tbody tr#new_row_" + i);
for (j = 0; j < 56; j++) {
var sclass = "";
if (j == 0)
$lasttr.append("<td>" + areas[i].AreaName + "</td>");
if (j == 1)
$lasttr.append("<td>" + areas[i].AreaSubName + "</td>");
if (j == 2)
$lasttr.append("<td>" + areas[i].AreaParentName + "</td>");
if (j > 2) {
sclass = "'scheddata'";
k = j - 2;
$lasttr.append("<td class=" + sclass + " HID='W" + k + "_" + year + "_" + areas[i].AreaID + "'></td>");
}
}
}
but it's not fast enough- and the problem with hovering remains. (also when using css :hover pseudoclass.
Can you do something like this?
$(function () {
for (i = 0; i < 56; i++)
$("thead tr").append("<th>" + (i+1) +"</th>");
for (i = 0; i < 20; i++){
$("tbody").append("<tr />");
for (j = 0; j < 56; j++)
$("tbody tr:last-child").append("<td>" + ((i+1) + ": " + (j+1)) +"</td>");
}
});
table tr:hover td {background: #99f;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
<thead><tr></tr></thead>
<tbody></tbody>
</table>

Getting the table row values with jQuery

I am trying to get the values from an HTML table row. When I click on the table row delete button, I want to put those values on variables to send to the server. I have found something from here that looks like what I need, but when I put it together for my scenario, it does not work.
Here is the table HTML:
<table id='thisTable' class='disptable' style='margin-left:auto;margin-right:auto;' >
<tr>
<th>Fund</th>
<th>Organization</th>
<th>Access</th>
<th>Delete</th>
</tr>
<tr>
<td class='fund'>100000</td><td class='org'>10110</td><td>OWNED</td><td><a class='delbtn'ref='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>170252</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67150</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67120</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a>
</td>
</tr>
and here is the jQuery:
var tr = $('#thisTable').find('tr');
tr.bind('click', function(event) {
//var values = '';
// tr.removeClass('row-highlight');
var tds = $(this).addClass('row-highlight').find('td');
$.each(tds, function(index, item) {
values = values + 'td' + (index + 1) + ':' + item.innerHTML + '<br/>';
alert(values);
});
alert(values);
});
What am I doing wrong? I keep looking at examples but I cant seem to make this work.
Try this:
jQuery('.delbtn').on('click', function() {
var $row = jQuery(this).closest('tr');
var $columns = $row.find('td');
$columns.addClass('row-highlight');
var values = "";
jQuery.each($columns, function(i, item) {
values = values + 'td' + (i + 1) + ':' + item.innerHTML + '<br/>';
alert(values);
});
console.log(values);
});
DEMO
Give something like this a try:
$(document).ready(function(){
$("#thisTable tr").click(function(){
$(this).find("td").each(function(){
alert($(this).html());
});
});
});​
Here is a fiddle of the code in action: https://jsfiddle.net/YhZsW/
All Elements
$('#tabla > tbody > tr').each(function() {
$(this).find("td:gt(0)").each(function(){
alert($(this).html());
});
});
Here is a working example. I changed the code to output to a div instead of an alert box. Your issue was item.innerHTML I believe. I use the jQuery html function instead and that seemed to resolve the issue.
<table id='thisTable' class='disptable' style='margin-left:auto;margin-right:auto;' >
<tr>
<th>Fund</th>
<th>Organization</th>
<th>Access</th>
<th>Delete</th>
</tr>
<tr>
<td class='fund'>100000</td><td class='org'>10110</td><td>OWNED</td><td><a class='delbtn'ref='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>170252</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67150</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67120</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a>
</td>
</tr>
</table>
<div id="output"></div>​
the javascript:
$('#thisTable tr').on('click', function(event) {
var tds = $(this).addClass('row-highlight').find('td');
var values = '';
tds.each(function(index, item) {
values = values + 'td' + (index + 1) + ':' + $(item).html() + '<br/>';
});
$("#output").html(values);
});
$(document).ready(function () {
$("#tbl_Customer tbody tr .companyname").click(function () {
var comapnyname = $(this).closest(".trclass").find(".companyname").text();
var CompanyAddress = $(this).closest(".trclass").find(".CompanyAddress").text();
var CompanyEmail = $(this).closest(".trclass").find(".CompanyEmail").text();
var CompanyContactNumber = $(this).closest(".trclass").find(".CompanyContactNumber").text();
var CompanyContactPerson = $(this).closest(".trclass").find(".CompanyContactPerson").text();
// var clickedCell = $(this);
alert(comapnyname);
alert(CompanyAddress);
alert(CompanyEmail);
alert(CompanyContactNumber);
alert(CompanyContactPerson);
//alert(clickedCell.text());
});
});

Categories