Agustin Agustin - 6 months ago 7
Javascript Question

Use Jquery to Detect length of Table for specific description

I have piece of code that is working fine but I want to refine it to detect the length of a table and give a description based on that.

This is a product catalog basically, where I use wordpress entries to show
a description of the product. Most entries contain a table, some do not. If a table exist, a link to specific point in the table is created and when clicked the visitor goes there. When NO table is detected a description to that effect is given.

The refinement I want to make is to add an additional condition where if the length of the table is, lets say, only 4 rows or less there is a different description for that condition such as

elTitulo.after("<a href='#tablesp' class='speclink'>Ver BREVE Tabla de Especificaciones</a> "); (BREVE = BRIEF)


and I am not sure how to integrate that part.
Does it require a condition inside the existing condition? Or a whole new condition?

<script>
jQuery(document).ready(function($) {
var elTitulo = $(".entry-title");
$("tbody").before("<div id='tablesp'></div>");
if ($('table').length) {
elTitulo.after("<a href='#tablesp' class='speclink'>Ver Tabla de Especificaciones</a> ");
} else {
elTitulo.after("<p class='speclink'>(No hay tabla especial de especificaciones. Breve descripciĆ³n disponible)</p> ");
}
});
</script>

Answer

This should work, but your code assumes there is only one table in the page. Also, adding a div insight your tbody is also not a good idea.

jQuery(document).ready(function($) {
    var elTitulo = $(".entry-title");
    $("tbody").before("<div id='tablesp'></div>");
    if ($('table').length) {

      if($('table tbody tr').length < 4){
        // There are less then 4 rows (not including 4)
        elTitulo.after("<a href='#tablesp' class='speclink'>Ver BREVE Tabla de Especificaciones</a> ");
      } else {
        elTitulo.after("<a href='#tablesp' class='speclink'>Ver Tabla de Especificaciones</a> ");
      }

    } else {
        elTitulo.after("<p class='speclink'>(No hay tabla especial de especificaciones. Breve descripciĆ³n disponible)</p> ");
    }
});
Comments