Hide part of a text with javascript

Asked

Viewed 2,270 times

4

I have a table that is filled with data from a bank. One of the columns contains text that is sometimes long ( more than 1000 characters). I want to limit the display of this text in the table to 300 characters and add a "read more" button if the user wants to display the rest.

I know you can do this by adding a markup to the text with HTML and the function toggle jQuery, but as the text comes from the database, I cannot insert this tag.

Is there any other way?

  • How you populate the data on the screen?

  • Return the query data to the database, printing with PHP

1 answer

4


Take advantage of date attributes to make your life easier, in this case the button to show more data-mais will have the full text and button to show less data-menos will have the text limited, depending on which one of them clicks the corresponding text will be 'injected' from td with class hide-text belonging to the same line. See if it fits your problem

$('.mais').on('click', function() {
  $(this).parent().parent().find('.hide-text').html($(this).data('mais'));
});
$('.menos').on('click', function() {
  $(this).parent().parent().find('.hide-text').html($(this).data('menos'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
  <td>1</td>
  <td class="hide-text">STO</td>
  <td><button data-mais="ISTO é o texto completo1" class="mais">Mostrar mais</button>
<button data-menos="STO" class="menos">Mostrar menos</button></td>
</tr>
<tr>
  <td>2</td>
  <td class="hide-text">STO</td>
  <td><button data-mais="ISTO é o texto completo2" class="mais">Mostrar mais</button>
<button data-menos="STO" class="menos">Mostrar menos</button></td>
</tr>
<tr>
  <td>3</td>
  <td class="hide-text">STO</td>
  <td><button data-mais="ISTO é o texto completo3" class="mais">Mostrar mais</button>
<button data-menos="STO" class="menos">Mostrar menos</button></td>
</tr>
</table>
<br>

EXAMPLE in jsfiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.