Deleting table row by id with jQuery - javascript

I dont't get why this code isn't working. Table row should be removed, but it's not. Confirm box is showing ok.
Maybe I have something wrong with row id or var elementId - I'm not sure.
<table> // some table code missing in this example because it's not necessary
<tr id="orderEmpty" style="display: none;"><td><i class="text-muted">No items.</i></td></tr>
<tr id="00001"><td>Delete</td></tr>
</table>
<script>
function deleteRow($rowToDel) {
var result = confirm("Are you sure? Delete row from order?");
if (result) {
var elementId = $rowToDel;
var rowCount = $('#orderTable tbody tr').length;
if (rowCount < 3) {
$('#' + $rowToDel + '').closest('tr').remove();
$("#orderEmpty").fadeIn();
} else {
$('#' + $rowToDel + '').closest('tr').remove();
}
}
}
</script>

Your example code as given already works for me; please see this jsFiddle: https://jsfiddle.net/v30fv89t/
I suspect that the actual markup you're working with is longer, but in the example you gave, rowCount will always be 0 because there is no #orderTable or tbody, and so that branch will always execute when deleteRow() is called.
If you can, please post a more extensive version of your markup - at least extensive enough so that your code fully tests against the markup you're working with.

If you remove .closest('tr') it should work. You already select the tr you're trying to delete with the jQuery constructor.
Also + '' is unnecessary as int is converted to a sting when it's added to one (in this case '#').

Related

While loop and toggling table header

I have a table with <theader>. Underneath each header, my PHP generates a <tbody> My goal is to toggle the <tbody> underneath each of these headers once the user clicks on the Table Header. Each <theader> has a unique id and so does the <tbody> that corresponds to it. So for example the header is #GenEdCategory1 and clicking on it will toggle #GenEdCourses1. and so on for #GenEdCategory2 and #GenEdCourses2 ...
I used these selectors for jQuery to do the toggling.
When I hardcode it, it works fine! Clicking on #GenEdCategory1 will toggle the #GenEdCourses1. But I want to make it dynamic based on the number of headers that have been fetched, I can't toggly anything!
I do this using a while loop but when I code it, it stops working. Any insight would be greatly appreciated! Cheers :)
var numberCategory = $('[id^=GenEdCategory]').length; //calculates number of GenEdCategories
var idCntr = 1; //GenEdCategory ctr
var cool = "#GenEdCategory" + idCntr; //click on this to toggle
var cool2 = "#GenEdCourses" + idCntr; //I want to toggle this
while (idCntr < numberCategory) {
$(document).on("click", cool, function(){
$(cool2).toggle();
});
idCntr = idCntr + 1;
cool = "#GenEdCategory" + idCntr;
cool2 = "#GenEdCourses" + idCntr;
};
};
};
Here's the HTML Snippet of the table I'm working with:
You can use jQuery's DOM traversal function to do it in a single function, not a loop, and there's no need to give them IDs.
$("thead").click(function() {
$(this).next("tbody").toggle();
});
BTW, <theader> should be <thead>.

delete rows between tables with identical tr id

I have two tables and with same tr ids and content (for some reason)!
When I click a check a box in table1 I should be able to delete that row in both table1 and table2 etc. How can I achieve this?
I can delete from table1 using
table1.on('click','tr .lowBox:checked',function(){
$(this).closest('tr').remove();
}
How do I delete row from table2.
thanks!
table1.on('click','tr .lowBox:checked',function(){
$(this).closest('tr').remove(); //send to var to perform as below
$("table2").closest('tr').remove(); //If you're traversing UP
$("table2").find('tr').remove(); //If you're traversing DOWN
//Inside your "click" event, you can traverse any part of the DOM
//regardless of where you entered the document with your click event
//slightly more robust, you could do this..
/*or as fed variables...e
var $item1 = $(this).closest('tr');
var $item2 = $("table2").closest('tr');
var $rmTwo = function(item1,item2){
$(item1).remove();
$(item2).remove();
}
//Then execute your repeatable function, using the two tr's
$rmTwo($item1,$item2);
// should remove both, and you can play
//with your jQuery to get the correct elements
//or alter them if you change your code structure.
}
This would be the closest I can get you without seeing any of your HTML, and under the assumption that you're using jQuery on your page.
As others have commented, you shouldn't have duplicate IDs. Instead you could use classes, or generate IDs that are unique (for example, by prefixing with the table id). However, if you must do it this way, here's what you could do:
table1.on('click','tr .lowBox:checked',function(){
var row = $(this).closest('tr');
table2.children("#" + row[0].id).remove();
row.remove();
}
If you switch to table-unique classes for each row:
table1.on('click','tr .lowBox:checked',function(){
var row = $(this).closest('tr');
table2.children("." + row[0].className).remove();
row.remove();
}
This solution makes a few assumptions about the structure of your HTML. I can update it if you post a more detailed sample of your HTML.
I solved this with:
table1DT=var $('#table1').dataTable({});
table2DT=var $('#table2').dataTable({});
table1DT.on('click','tr .lowBox:checked',function(){
var row= $(this).closest('tr');
//do some thing with row variable
var d=row.attr('id');
var nRow = $('#table2 tbody tr[id='+d+']')[0];
table2DT.fnDeleteRow(nRow);
table1DT.fnDeleteRow(row);
}
so checking the table1 check box would delete that particular row in table1 and table2 etc.

How to dynamically remove records from a table via Jquery

I have an html table that is dynamically created.
The following jQuery code captures the tr that the user has selected in that table, and populates another table called "selected_users" with specific data from the row that's been picked.
$('#available_users tbody').on('click', 'tr', function () {
var id = this.id;
var tr;
tr=$('<tr/>');
var index = $.inArray(id, selected);
if ( index === -1 ) {
selected.push( id );
var tds = $(this).find('td');
tr.append("<td>" + tds.eq(1).text() + "</td>");
tr.append("<td>" + tds.eq(3).text() + "</td>");
$('#selected_users').append(tr);
} else {
selected.splice( index, 1 );
}
$(this).toggleClass('selected');
} );
Question
This logic is working. But now what I need to do is when users deselect a previously selected record from the available_users table, I need to remove it from the "selected_users" table.
What I've tried So far:
The first thing I tried to do is to assign an ID to the <TR> that I create in the "selected_users" table, so that I can use this id to find the row I want to delete.
I tried to change my code to look like this:
var index = $.inArray(id, selected);
if ( index === -1 ) {
selected.push( id );
var tds = $(this).find('td');
tr.append("<td>" + tds.eq(1).text() + "</td>");
tr.append("<td>" + tds.eq(3).text() + "</td>");
tr.attr('id') = id.substring(4); //******* NEW ********
$('#selected_users').append(tr);
But it bombs with an error "ReferenceError: invalid assignment left-hand side".
The other question is how to remove the from the selected_users table. I'd like to put the logic in the else path ...
} else {
selected.splice( index, 1 );
//*** add logic to remove also from the selected_users table.
}
Thanks.
EDIT 1
All the code I've posted here works, except the attempt to dynamically assign the ID attribute to the new <TR> I'm adding. I think in this case, all the details might be making things more complicated ???
Maybe it would simplify things if I just asked how do so something like this:
var tr;
tr.append("<td>value1</td>");
$('#test_table').append(tr);
When doing something like the above, how would you assign an id of "id=123" to the <tr>?
Also, if you only had the row id (<tr id=123>), how could you delete the entire row from test_table?
First, I'm assuming that this is the line that "bombs with an error ReferenceError: invalid assignment left-hand side":
tr.attr('id') = id.substring(4);
I make this assumption because attr('id') will return a String, which is immutable, and you're trying to assign a new String (of id.substring(4)) to that existing string.
If you wish to set a new value to the id you need to use the setter form of the attr() method:
tr.attr('id', id.substring(4))`
Or, assuming the substring is to be taken from the current id:
tr.attr('id', function (index, currentProperyValue) {
return currentPropertyValue.substring(4);
});
In the above the argument-names are user-defined, the first argument (above: 'index') is the index of the current element returned by the collection in the tr variable; the second (above: 'currentPropertyValue') represents the current-value of the property we're changing with the method.
…if you only had the row id (<tr id=123>), how could you delete the entire row from test_table?
Simply, using jQuery:
$('#123').remove();
Which will remove the element from the document (wherever that element appears within the document, bearing in mind that duplicate ids are invalid, so if two elements occur with that same id only the first element with that id will be removed).
Alternatively, but still simply, using plain JavaScript; here we're using a variable because we need to get the same element twice:
var elem = document.getElementById('123');
elem.parentNode.removeChild(elem);
References:
JavaScript:
document.getElementById().
Node.parentNode.
Node.removeChild().
String.
String.prototype.substring().
jQuery:
attr().
remove().

get the amount of rows in a table

I want to get the amount of rows in a table on my page.
I am trying to do this using .execute(function(){}) but how is it possible to get a variable out of the execute function and use it there.
this isn't the counter yet, buy i can't even get a variable to work.
i tried something like this:
.execute(function(){
global.amountOfRows = 5;
})
.assert.numberOfElements('#content-list > tbody > tr', global.amountOfRows)
i tried the same using var amountOfRows = 5;
Any ideas?
Using jquery to return the number of row in your table body
$('#your_table_id tbody').find('tr').length;
http://api.jquery.com/length/
I tried this but it didnt work out as planned.
Using jquery to return the number of row in your table body
$('#your_table_id tbody').find('tr').length;
http://api.jquery.com/length/
unfortunately Dalek doesn't has the capability to do assertions on data you did get out of a execute statement at the moment, but there is a workaround for you ;)
.execute(function(){
// store as a `data` var
this.data('amountOfRows', 5);
})
// doSomeOtherStuff
.execute(function () {
// using jquery here to keep it short
var actualNumberOfRows = $(''#content-list > tbody > tr').length;
// do an "in browser" assertion
this.assert.ok((actualNumberOfRows === this.data('amountOfRows')), 'Amount of rows is as expected');
})
.done();
You can find further info on this undocumented API here:
https://github.com/asciidisco/jsdays-workshop/blob/5-js/test/dalek/javascript.js#L16-L29

How to use jQuery to dynamically update IDs after cloning a table row?

When triggered, the 3rd (bottom) row of a table is cloned. In the CSS, this row (#tr3) is set to: display:none; Here is the table row I am cloning:
<tr name="tr3" id="tr3">
<td><input type="text" name="dt1" id="dt1"></td>
<td><input type="text" name="fn1" id="fn1"></td>
<td>change</td>
<td>delete</td>
</tr>
This is the JQuery code to clone the row. Not mine, sadly, so I don't understand all of it.
$("table tr:nth-child(4)").clone().find("input").each(function() {
$(this).val('').attr('id', function(_, id) {
return id + count;
});
Specifically, how does the function in line 2 work - what is the underscore?
Here's what I came for, though. How can I:
change the style to display:block for cloned rows, and
update the ids of the anchor tags in the cloned rows. The IDs of the input fields Do update (e.g. fn1 => fn11, fn12, fn13, fn14, etc).
Thank you.
Just for clarity:
var $clone = $("table tr:nth-child(4)").clone();
How to change the style to display:block for cloned rows?
$clone.show();
How to update the ids of the anchor tags in the cloned rows.
$clone.find("a, input").each(function() {
$(this).val('').attr('id', function(_, id) {
return id + count;
});
});
In the jQuery code above, how does the function in line 2 work - what is the underscore?
The underscore (_) is a valid ECMAScript's identifier name and it is used simply as a placeholder to be able to grab the second argument (id.)
And everything altogether (untested.)
$("table tr:nth-child(4)")
.clone()
.show()
.find("a, input").each(function() {
$(this).val('').attr('id', function(_, id) {
return id + count;
});
});
You never actually access the cloned row on its own. You would have to assign it to something, e.g.
$clonedRow = $("table ...").clone();
then you can run all of the other methods and finally append $clonedRow to the DOM, possibly with
$clonedRow.insertAfter("table ...")
You need to somehow strip off the last digit(s), possibly with a regex:
return id.replace(/\d+$/, '') + count;
The _ is just a placeholder. It's not used, so the writer of the code chose a nondescript variable name since something is required in the declaration to get at the id parameter.

Categories