Pregunta

I need to append columns to an HTML table in a specific location. This topic discusses doing that - pretty handy! My problem is that the columnCount() function shown below does not have the ability to target a specific table. It counts all TDs present in the HTML which ends up causing problems when generating an index value.

function countColumn() {
   var colCount = 0;
   $('tr:nth-child(1) td').each(function () {
       if ($(this).attr('colspan')) {
           colCount += +$(this).attr('colspan');
       } else {
           colCount++;
       }
   });
   return colCount;
}

I have two JS fiddles.

  • One functions because there is only one table.
  • The second one does not function because there are two tables present.

    The second fiddle returns an invalid colCount value and cannot place the column inside of the target table. I am still too green on selectors to be able to apply the correct selector in context... I am slowly learning this language.

Edit: Link to the JSFiddle that has the corrected code. I hope this helps someone else who is struggling with selector syntax!

¿Fue útil?

Solución

Take the table ID as a parameter:

function countColumn(tableID) {
   var colCount = 0;
   $('#' + tableID + ' tr:nth-child(1) td').each(function () {
       if ($(this).attr('colspan')) {
           colCount += +$(this).attr('colspan');
       } else {
           colCount++;
       }
   });
   return colCount;
}

You could also define a jQuery method that operates on a selector:

$.fn.colCount = function() {
   var colCount = 0;
   $('tr:nth-child(1) td', this).each(function () {
       if ($(this).attr('colspan')) {
           colCount += +$(this).attr('colspan');
       } else {
           colCount++;
       }
   });
   return colCount;
};

Then you can do var count = $("#someTable").colCount();

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top