get the amount of rows in a table - javascript

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

Related

Deleting table row by id with jQuery

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 '#').

How to refresh datatable column data

I use data table plugin with table as data source. I have to change some column value via javascript when the user types in some numbers into an input (this input is part of the table too and I have to export this values to). It is working well but when I want to export the table the columns witch was changed with javascript is not displayed in the exported file.
I think the problem is that I have not refreshed the datatable plugin. Is this correct? If yes how do I refresh the datasource? If no what can be the problem and how can I solve it?
I tried the refresh() method (var dataTableObject = $(this).parents('table').dataTable(); dataTableObject.refresh();) and the $(this).parents('table').dataTable() but is not working.
Edit: Here is how do I change the cell value:
$item.find('input.quantity-coefficient').each(function (i, d) {
$(d).off('change').on('change', function () {
var multiplier = $(this).val();
//var dataTableObject = $(this).parents('table').dataTable();
$($(this).data("row-price-info-class")).each(function (i, d) {
var priceContainer = $(d);
var price = parseFloat(priceContainer.data('price-value'));
var priceInfoRatioContainer = $(priceContainer.data("ratio-input-class"));
if (multiplier * price == 0) {
priceInfoRatioContainer.closest("td").addClass("no-euro");
priceInfoRatioContainer.html(" ");
} else {
priceInfoRatioContainer.closest("td").removeClass("no-euro");
priceInfoRatioContainer.html(localizeNumber(multiplier * price));
}
});
//TODO redrow the data
$(this).parents('table').dataTable().fnDraw();;
});
});
You can refresh the dataTable with fnDraw(). In your example:
$(this).parents('table').dataTable().fnDraw();
Thank you guys but I think I found the solution in this post: jquery DataTables - change value of a cell not just display value
When I tried it on the first time the problem was that I started the row numbering from 1 and not from 0.
So for the others who may have this issue to, I have to use something like this:
(this).parents('table').dataTable().fnUpdate("new value", 0, 2)
To update the cell value. Actually this is not what I asked because this is not refresh all the table, but this is a solution for me now.

Remove rows from a table which I collected from a loop (JQuery)

I have a table that I loop with JQuery in order to find rows that match certain conditions:
$('#sometable').find('tr').each(function () {
var row = $(this); //<----
if(row.find('input[type="checkbox"]').is(':checked')) {
//etc
}
}
My question is, is there a way to remove each matched row? I mean is there a way to collect these row variables inside my if(row.find('input[type="checkbox"]').is(':checked')) so that I can remove the specific rows from my table directly?
Note that my rows don't have a unique id
You may want:
$('#proposedtable tr:contains(input:checkbox:checked)').remove();
or
$('#proposedtable input:checkbox:checked').closest('tr').remove();
Try this:
var filteredRows = $('#sometable').find('tr').filter(function(){
return $(this).find('input[type="checkbox"]').is(':checked'));
});
$(filteredRows).remove();
The above function will gather all the rows(tr) and then filter those rows based on the checked state of checkbox. Later the filtered rows will be removed.
To make it as array, use Array.prototype.slice.call()
var arrFilteredRows = Array.prototype.slice.call(filteredRows);
Is this help you ?
http://jsfiddle.net/LGdA3/
<pre><code>
$('input#myButton').on('click', function(){
$('table#someTable td input[type="checkbox"]:checked').each(function(){
$(this).parents('tr').first().remove();
});
});
</code></pre>

Can't get javascript/jquery to sort elements correctly more than one time

I have child divs that I'm trying to sort based on a jquery .data() value that I give them that is just a single number. This code works perfectly, but only once, after that I can't figure out how the heck it's sorting them. Here is a simplified version:
var myArray = $('#container div').get();
myArray.sort(function(x,y) {
return $(x).data('order') - $(y).data('order');
});
$('#container').empty().append(myArray);
I've tried so many other different methods of sorting, other plugins, etc., and I can't get anything to work right. This is as close as I can get. I just have this running on a jquery change event.
Here is the whole thing in case I'm doing something stupid elsewhere:
$('#attorneyFilter').change(function() {
//get array of links for sorting
var myArray = $('#attorneyBlocks div').get();
var selectedArea = $(this).val();
//sort alphabetically when "all" is selected
if (selectedArea == 'all') {
$('#attorneyBlocks div').show();
myArray.sort(function(a,b) {
return $(a).text() > $(b).text() ? 1 : -1;
});
//filter attorneys based on practice area and then assign its order# to the div with data, getting all values from the div's class
} else {
$('#attorneyBlocks div').hide().each(function() {
var attorneyArea = $(this).attr('class').split(', ');
for (var i=0;i<attorneyArea.length;i++) {
var practiceArea = attorneyArea[i].split('-');
if (selectedArea == practiceArea[0]) {
$(this).show().data('order',practiceArea[1]);
}
}
});
//sort based on order, the lower the number the higher it shows up
myArray.sort(function(x,y) {
return $(x).data('order') - $(y).data('order');
});
}
//append order back in
$('#attorneyBlocks').empty().append(myArray);
});
And a link to the page in question
Here's a jsFiddle with this working using .detach() instead of .empty() to keep the data.
http://jsfiddle.net/shaneblake/Tn9u8/
Thanks for the link to the site, that made it clear.
It seems to me you never clear out the data from the prior time. You hide everything but maybe something like this will solve your problem (here I set everything hidden to the bottom, you can clear it or use a different value -- as long as it is not the same as any sort key):
$('#attorneyBlocks div').hide().data('order',999999).each(function() {
var attorneyArea = $(this).attr('class').split(', ');
for (var i=0;i<attorneyArea.length;i++) {
var practiceArea = attorneyArea[i].split('-');
if (selectedArea == practiceArea[0]) {
$(this).show().data('order',practiceArea[1]);
}
}
});
Also, the code on the server is missing the 2nd line you have above:
var myArray = $('#attorneyBlocks div').get();
The problem is the change event is tied to the original items. After the sort you make all new items. They don't have any event tied to them. You will need to use .live()
Eventually figured it out, the data values from hidden divs were screwing with my sorting, so I changed my sorting code to only pay attention to :visible divs and that did the trick. Doh! Thanks for your help everyone.

How can I hide empty html table cells with jQuery?

I have a 5×7 HTML table. On many queries, there are fewer than 35 items filling the complete table.
How can I "hide" the empty cells dynamically in this case, using jQuery (or any other efficient way)?
Edit - Improved Version
// Grab every row in your table
$('table#yourTable tr').each(function(){
if($(this).children('td:empty').length === $(this).children('td').length){
$(this).remove(); // or $(this).hide();
}
});
Not tested but seems logically sound.
// Grab every row in your table
$('table#yourTable tr').each(function(){
var isEmpty = true;
// Process every column
$(this).children('td').each(function(){
// If data is present inside of a given column let the row know
if($.trim($(this).html()) !== '') {
isEmpty = false;
// We stop after proving that at least one column in a row has data
return false;
}
});
// If the whole row is empty remove it from the dom
if(isEmpty) $(this).remove();
});
Obviously you'll want to adjust the selector to fit your specific needs:
$('td').each(function(){
if ($(this).html() == '') {
$(this).hide();
}
});
$('td:empty').hide();
How about CSS empty-cells
table {
empty-cells: hide;
}
I'm voting for Ballsacian's answer. For some reason,
$('table#myTable tr:not(:has(td:not(:empty)))').hide();
has a bug. If you remove the outermost :not(), it does what you'd expect, but the full expression above crashes jQuery.

Categories