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
Related
I want to alter HTML Table row which is inserted by dynamically.
At beginning there will no rows in table.
HTML Code
<table class="table table-hover " id="queryTable">
<thead>
<tr>
<th>Field Name</th>
<th>Values</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JQUERY Code
//SELECT Table ROW
$(document).on("click", '#queryTable tbody tr', function () {
var tr = $(this);
var FieldName = tr.find("td:first").text();
var Values = tr.find("td:last").text();
FieldName = FieldName.replace('AND ', '');
FieldName = FieldName.replace('OR ', '');
Values = Values.replace('IN(', '');
Values = Values.replace(')', '');
$("#FilterField option[value=" + FieldName + "]").attr("selected", true);
$("#FilterField").val(FieldName);
$("#txtFilterValue").val(Values); //FilterValue textbox id
});
$("#btnChange").click(function () {
td.text($("#txtFilterValue").val());
});
Those 3 records are added dynamically. When user wants to modify the value of any FieldName of Values ,Once user click that row from the table, the value will show on Filter Value textbox as you can see above.
In the above pic, User select second row. once the user change the value in textbox and when they click the Change button the second row should alter.
Assuming your table id as YOURTABLEID and your textbox id as FILTERVALUETEXTBOX
var td;
$(document).on("click","#YOURTABLEID td",function(){
td=$(this);
$("#FILTERVALUETEXTBOX").val($(this).text());
});
If you want to click on tr and want to get second td value, then
var td;
$(document).on("click","#YOURTABLEID tr",function(){
td=$(this).find("td:last"); //AS SECOND TD IS LAST
$("#FILTERVALUETEXTBOX").val(td.text());
});
Once you get your td value in textbox, Change button click event will be as follow
$("#btnChange").click(function(){
td.text($("#FILTERVALUETEXTBOX").val());
});
UPDATE
var td;//THIS IS MISSING IN YOUR CODE
$(document).on("click", '#queryTable tbody tr', function () {
var tr = $(this);
td=$(this).find("td:last");//THIS IS MISSING IN YOUR CODE
var FieldName = tr.find("td:first").text();
var Values = tr.find("td:last").text();
FieldName = FieldName.replace('AND ', '');
FieldName = FieldName.replace('OR ', '');
Values = Values.replace('IN(', '');
Values = Values.replace(')', '');
$("#FilterField option[value=" + FieldName + "]").attr("selected", true);
$("#FilterField").val(FieldName);
$("#txtFilterValue").val(Values); //FilterValue textbox id
});
$("#btnChange").click(function () {
td.text($("#txtFilterValue").val());
});
I am trying to remove a certain table row in a string. For instance, I have the code below in a string. Lets call the variable that stores the string below temp
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
I have several buttons with id's corresponding to the number of row above. If I click the first button it has a corresponding id of 1, the second button has 2, etc.
What I am getting at is that if I hit these delete buttons, I want to remove the corresponding table row above based on what id (button) I click.
Here is my code so far.
$(".delete").click(function() {
var id = $(this).attr("id");
var temp = $("#detailsBox").val();
for (i=1; i!=id; i++) {
if (i=1) {
}
}
$(this).closest('tr').remove();
}
How would I delete a part of that string in my variable temp based off of the id(button) I click? If I choose button 1, I want to delete the first table row. Button two, second table row, etc. I know I need to replace the string, but how do I remove certain instances within the string?
Parsing HTML is dangerous. Therefore I suggest you convert your string to DOM and then manipulate on the DOM tree.
Here is a simple solution with jQuery:
var row = 1; // the row I want to remove
var temp = $("#myTextarea").value(); // get HTML
var table = $("<tbody>" + temp + "<tbody>"); // creates DOM nodes from HTML
table.find("tr").eq(row - 1).remove();
var tempWithoutRow = table[0].innerHTML;
Try yourself in JSFiddle.
You are trying to use jQuery as if that elements are in DOM... and they are not. They are just one string. So you can do something like that:
var arr = yourString.split("<tr>");
$(".delete").click(function() {
var id = $(this).attr("id");
arr = arr.splice(parceInt(id, 10)-1, 1);
}
Now you have array with the right TRs inside. All you have to do is to convert them to string again:
var htmlString;
for (var i=0; i<arr.length; i++) {
htmlString += arr[i];
}
UPDATE jQuery WAY
You can do it with jQuery too. Look at the fiddle
http://jsfiddle.net/J6HJ2/2/
You can select all the table rows and then filter down to the one you want:
$(".delete").click(function() {
var id = $(this).attr("id");
$("#my-table").find("tr").eq(id + 1).remove();//since your IDs are not zero-indexed and .eq() is
});
Docs for .eq(): http://api.jquery.com/eq
$(".delete").click(function() {
var id = $(this).attr("id");
var temp = $("#detailsBox").val();
for (i=1; i!=id; i++) {
if (i=1) {
}
}
$(this).parentNode.remove();
}
if the .delete is on the td
else if u have <td><button class="delete"></button></td>
then it's $(this).parentNode.parentNode.remove();
no need for the id if the button is inside the <tr>
Easy solution would be to give the rows meaningful ID's and use the following code:
$(".delete").click(function() {
$('#row' + $(this).id).remove();
}
If you really want to count nameless TR elements in a string you could split them into an array with split("<tr>")
I have a table to which I am currently dynamically adding rows: http://jsfiddle.net/fmuW6/5/
Now I'd like to add a new column to the table as well with a click of a button. The user will enter the column header in a textbox.
How can I achieve this? If the user adds 4 rows, the Add a new Column button should take care of all the existing rows (adding checkbox in each one).
update
I'm looking to add column name and checkbox at row level.
so I've added the text box in which the user will input the column name: http://jsfiddle.net/fmuW6/10/
<input type=text placeholder='columnname'/>
<button type="button" id="btnAddCol">Add new column</button></br></br>
so then when user clicks the button the columnname should be the value in the textbox and at the row level should be checkboxes. So basically the new column should be appended to all tr in the table except the first row since that is the column names
I updated your fiddle with a small example how you could do that.
jsFiddle - Link
var myform = $('#myform'),
iter = 0;
$('#btnAddCol').click(function () {
myform.find('tr').each(function(){
var trow = $(this);
if(trow.index() === 0){
trow.append('<td>Col+'iter+'</td>');
}else{
trow.append('<td><input type="checkbox" name="cb'+iter+'"/></td>');
}
});
iter += 1;
});
This would add a new column to every row, including an count-variable that gets applied to the first row as name and to the name-attribute of the checkboxes on the following rows.
Consider using th - elements for the table header, that way you wouldn't need the index-check i'm making and it would be more semantically correct.
I left out the part where the user would put in a name for the column, but as you see, you could just replace the iter - value with that in the end.
Modern pure JavaScript solution:
const addColumn = () => {
[...document.querySelectorAll('#table tr')].forEach((row, i) => {
const input = document.createElement("input")
input.setAttribute('type', 'text')
const cell = document.createElement(i ? "td" : "th")
cell.appendChild(input)
row.appendChild(cell)
});
}
document.querySelector('button').onclick = addColumn
<table id="table">
<tr><th><input type="text" value="test 1" /><th/></tr>
<tr><td><input type="text" value="test 2" /><td/></tr>
</table>
<button type="button">add column</button>
First row will contain a th instead of td. Each new cell contains a input. Feel free to change this to suit your need.
The answer works, but still here is an alternative way where we use thead and tbody !
JS
$('#irow').click(function(){
if($('#row').val()){
$('#mtable tbody').append($("#mtable tbody tr:last").clone());
$('#mtable tbody tr:last :checkbox').attr('checked',false);
$('#mtable tbody tr:last td:first').html($('#row').val());
}
});
$('#icol').click(function(){
if($('#col').val()){
$('#mtable tr').append($("<td>"));
$('#mtable thead tr>td:last').html($('#col').val());
$('#mtable tbody tr').each(function(){$(this).children('td:last').append($('<input type="checkbox">'))});
}
});
Use this code for adding new column:
$('#btnAddCol').click(function () {
$("tr").append("<td>New Column</td>");
});
But you need to change the value for the first row with a text and others to include a <input type="checkbox" />. And it is better to
Check it out jsFiddle .............................
http://jsfiddle.net/fmuW6/8/
$(document).ready(function () {
$('#btnAdd').click(function () {
var count = 3, first_row = $('#Row2');
while(count-- > 0) first_row.clone().appendTo('#blacklistgrid');
});
$('#btnAddCol').click(function () {
$("#blacklistgrid tr").each(function(){
$(this).append("<td>test</td>");
})
});
});
Using a table of 4 columns:
I can add values dinamically like this:
var TableId = "table_" + id;
var table = $("#" + TableId );
table.find("tbody tr").remove();
table.append("<tr><td>" + "1" + "</td><td>" + "lorem" + "</td><td>" + "ipsum" + "</td><td>" + "dolor" + "</td></tr>");
and the final result will be:
I have the current table data:
<table>
<tr class="Violão">
<td>Violão</td>
<td class="td2 8">8</td>
</tr>
<tr class="Violão">
<td>Violão</td>
<td class="td2 23">23</td>
</tr>
<tr class="Guitarra">
<td>Guitarra</td>
<td class="td2 16">16</td>
</tr>
</table>
What I want to do is groupby the TDs which are the same, and sum the values on the second td to get the total. With that in mind I´ve put the name of the product to be a class on the TR (don't know if it is needed)
and I've coded the current javascript:
$(".groupWrapper").each(function() {
var total = 0;
$(this).find(".td2").each(function() {
total += parseInt($(this).text());
});
$(this).append($("<td></td>").text('Total: ' + total));
});
by the way the current java scripr doesn't groupby.
Now i'm lost, I don't know what else I can do, or if there is a pluging that does what I want.
</tr class="Violão"> This doesn't make sense. You only close the tag: </tr>. And I'm assuming you know that since the rest of your code is proper (except for your classnames. Check this question out).
If you want to add the values of each <td> with a class of td2, see below.
Try this jQuery:
var sum = 0;
$(".td2").each(function(){
sum = sum + $(this).text();
});
This should add each number within the tds to the variable sum.
<table>
<tr class="Violão">
<td>Violão</td>
<td class="td2 8">8</td>
</tr>
<tr class="Violão">
<td>Violão</td>
<td class="td2 23">23</td>
</tr class="Violão">
<tr class="Guitarra">
<td>Guitarra</td>
<td class="td2 16">16</td>
</tr>
</table>
var dictionary = {};
$("td").each(function(){
if(!dictionary[$(this).attr("class"))
dictionary[$(this).attr("class")] = 0;
dictionary[$(this).attr("class")] += parseInt($(this).html());
});
// declare an array to hold unique class names
var dictionary = [];
// Cycle through the table rows
$("table tr").each(function() {
var thisName = $(this).attr("class");
// Add them to the array if they aren't in it.
if ($.inArray(thisName, dictionary) == -1) {
dictionary.push(thisName);
}
});
// Cycle through the array
for(var obj in dictionary) {
var className = dictionary[obj];
var total = 0;
// Cycle through all tr's with the current class, get the amount from each, add them to the total
$("table tr." + className).each(function() {
total += parseInt($(this).children(".td2").text());
});
// Append a td with the total.
$("table tr." + className).append("<td>Total: " + total + "</td>");
}
Fiddler (on the roof): http://jsfiddle.net/ABRsj/
assuming the tr only has one class given!
var sums = [];
$('.td2').each(function(){
var val = $(this).text();
var parentClass = $(this).parent().attr('class');
if(sums[parentClass] != undefined) sums[parentClass] +=parseFloat(val);
else sums[parentClass] = parseFloat(val);
});
for(var key in sums){
$('<tr><td>Total ('+key+')</td><td>'+sums[key]+'</td></tr>').appendTo($('table'));
}
I would give the table some ID and change to appendTo($('#<thID>'))
The solution:
http://jsfiddle.net/sLysV/2/
First stick and ID on the table and select that first with jQuery as matching an ID is always the most efficient.
Then all you need to do is match the class, parse the string to a number and add them up. I've created a simple example for you below
http://jsfiddle.net/Phunky/Vng7F/
But what you didn't make clear is how your expecting to get the value of the td class, if this is dynamic and can change you could make it much more versatile but hopefully this will give you a bit of understanding about where to go from here.
Okay i have a HTML TABLE , with 4 TDs in a TR(tow) as shown in the code below:
<table>
<tr>
<td class="1">Lemon</td>
<td class="2">Orange</td>
<td class="3">Tea</td>
<td class="4">Get</td>
</tr>
<tr>
<td class="1">Apple</td>
<td class="2">Tomato</td>
<td class="3">Pineapple</td>
<td class="4">Get</td>
</tr>
</table>
How can i use jQuery to make , when a#GET is clicked , it will go get the class 1 , 2 , 3 values which is in the same table row as it.
For example , i click on the a#get in the first row , i will get Lemon , orange , tea as the results.
I use the jQuery code below but it's not working:
$(document).ready(function(){
$('a#get').click(function(e){
e.preventDefault();
var val1 = $(this).parent().find('td.1').html();
var val2 = $(this).parent().find('td.2').html();
var val3 = $(this).parent().find('td.3').html();
alert(val1 + val2 + val3);
});
});
Any ideas on how can i do this or what i'm doing wrong?
thanks!
See Working Demo
You should use unique id, here is modfifed code:
$(document).ready(function(){
$('a.get').click(function(e){
e.preventDefault();
var val1 = $(this).closest('tr').find('td.1').html();
var val2 = $(this).closest('tr').find('td.2').html();
var val3 = $(this).closest('tr').find('td.3').html();
alert(val1 + val2 + val3);
});
});
Using parent you were getting back to td because link is inside that, you needed to get back to tr which is done through closest('tr'). Also html has been modified for link element to have unique id.
Get
You're calling .find() inside the td element, while you actually need to call it in tr, which is one level higher.
Replace $(this).parent().find(...) with $(this).parent().parent().find(...).
(And you should make your IDs unique, as pimvdb suggested.)
There's no point adding a class to the cells, if they're just numerical - you can use eq() for that.
Here's how I'd do it:
$('#table-id tr').each(function() {
var tds = $(this).find('td');
$(this).find('a.get').click(function() {
alert(tds.eq(0).html() + tds.eq(1).html() + tds.eq(2).html());
return false;
});
});