Remove particular row of text in string based on id selected - javascript

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>")

Related

how to obtain the drop down selected option from a dynamic table

I am trying to extract selected option from a dynamically created table column. The code below works to extract the input values but not for the drop down values.
Dynamically generate HTML
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><input name='Letter"+i+"' type='text' placeholder='Letter' class='form-control input-md' /> </td><td><input name='Start"+i+"' type='text' placeholder='Start' class='form-control input-md'></td><td><input name='End"+i+"' type='text' placeholder='End' class='form-control input-md'></td> <td> <select name='cars' id='cars'><option value='All'>All</option><option value='Even'>Even</option><option value='Odd'>Odd</option></select></td>");
javascript code
// start from the second row as the first one only contains the table's headers
for (let i = 1; i < targetTableRows.length; i++) {
var Inventorydict ={}
// loop over the contents of each row
for (let j = 0; j < targetTableRows[i].cells.length; j++) {
// something we could use to identify a given item
let currColumn = tableHeaders.cells[j].innerHTML;
// the current <td> element
let currData = targetTableRows[i].cells[j];
// the input field in the row
let currDataInput = currData.querySelector('input');
// is the current <td> element containing an input field? print its value.
// Otherwise, print whatever is insside
currDataInput ? console.log(`${currColumn}: ${currDataInput.value}`)
: console.log(`${currColumn}: ${currData.document.getElementById("addressType")}`);
if (currDataInput) {
Inventorydict[currColumn.replace(/\s/g, '')] = currDataInput.value;
} else {
Inventorydict[currColumn.replace(/\s/g, '')] = currData.innerHTML;
}
}
I use this to get the input values
let currDataInput = currData.querySelector('input');
I tried using this to get the selected option
let addresstype = currColumn.getElementById("addressType")
but it does not work. How can I obtain the drop down selected option ?
currColumn is being given a value in this point of your code:
let currColumn = tableHeaders.cells[j].innerHTML;
The innerHTML property returns a string, that's why you cannot use querySelector on it.
First of all, if you want to get the value of the select once every row, you should move that section outside of that inner cycle, that loops through each cell of that row.
Then, you will need to get a reference of the tr html element. This should be targetTableRows[i].
You can get your select element by using the querySelector on this element:
for (let i = 1; i < targetTableRows.length; i++) {
var Inventorydict ={}
// ...
let select = targetTableRows[i].querySelector("select");
let selectValue = select.value; // This will map to the "value" property of the selected option
}
However, please keep in mind that you should really select elements based on their class or input name, not by their type. Also, you should not assign the same id to multiple element of your page. This will help you avoid errors that will be hard to troubleshoot.

SetVariable(var count, var count)

As the code below shows, I am appending a table with some table rows containing table data. The table data is getting appended with excel formula inside. How can I change the count variable inside td.class after it was appended in table upon click event or something similar.
I Want to update td.excel count attribute with onclick event
.append("<td class="
excel " x:num x:fmla=\"=SUM(H" + count + " *I" + count + ")
$("#example").on("click", "button", function() {
$(this).closest("tr").remove();
count--;
var i = 10;
for (i = 10; i < count; i++) {
let div1 = document.getElementsByClassName("excel");
var attribute = div1.SetAttribute(count, count);
}
}
Your problem is not clear. But what I've got from your question is that you want to dynamically append to . But you end up with excel formula getting inside it.
So, according to me when you want to insert something dynamically then you should use `` these quotes instead of '' and "". eg :-
var i = 1;
.append(`<td class="hello${i}"></td>`)

Get ids of checked check boxes in a form using pure javascript

I have a table- each row has a checkbox of name checkBoxDelete. The id of the check box is unique(used the customer id).
I would like to get all the unique ids that were selected. So, I started by gathering all the elements of the form. Then check if it is a checkbox that is checked. If it is ,then get it's id.
var elLength = document.deleteForm.elements.length;
for (var i=0; i<elLength; i++){
var type = deleteForm.elements[i].type;
if (type=="checkbox" && deleteForm.elements[i].checked){
var rowID=deleteForm.elements[i].id;
checkedIds += rowID + ";" ;
count++;
}
}
However, rowID is always ";".
I believe I am not getting a reference to the checkbox correctly.
Change this var rowID=deleteForm.elements[i].id; to var rowID= document.deleteForm.elements[i].id;
You forgot document before selecting deleteForm

Remove a row from Html table based on condition

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

Jquery group by td with same class

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.

Categories

Resources