Search code examples
jqueryjsonsubstr

Check if json parsed item string is larger than number


I'm trying to check if a parsed json item is greater than 17 characters, and if so, I need to display ellipses.

I am targeting item.tli below. As you will see, I'm trying to create a link. If the tli is greater than 17 characters, I only want to show 17 characters then display the ellipses after.

Here is the javascript:

$.post('api/displayRecords.php', function(data)
{
  var table = $('#example1').DataTable();
  table.search('').draw();
  var obj = JSON.parse(data);
  obj.forEach(function(item)
  {
    if(item.tli == null){item.tli = '';}
    table.row.add([item.booking, item.quote, '<a href="#">'+item.tli+'</a>', item.name])
  });
  table.draw();
});

As you can see above, if item.tli is null, then I won't display anything.

What I need to do now if figure out is if the tli is greater than 17, then show the 17 along with ellipses.

In PHP, I can do this:

<td><a href='#'>".substr($row['tli'],0,17)."...</a></td>

But I need to do it in jQuery now. I'm just not sure how to do it providing the first example above.


Solution

  • Try this:

    $.post('api/displayRecords.php', function(data)
        {
          var table = $('#example1').DataTable();
          table.search('').draw();
          var obj = JSON.parse(data);
          obj.forEach(function(item)
          {
            if(item.tli == null){item.tli = '';}
            else { 
                if (item.tli.length > 17) { 
                   item.tli = item.tli.substring(0, 17) + '...';
                } 
            }
            table.row.add([item.booking, item.quote, '<a href="#">'+item.tli+'</a>', item.name])
          });
          table.draw();
        });