Hide part of a text with javascript

3

I have a table that is populated with data coming 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 how to do this by adding a tag in the text with HTML and the toggle function of jQuery, but since the text comes from the database, I can not insert this markup.

Is there any other way?

    
asked by anonymous 15.06.2016 / 16:55

1 answer

3

Take advantage of date attributes to make life easier, in this case the button to show more data-mais will have the full text and the button to show less data-menos will have the text limited, depending on which one 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><tdclass="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

    
15.06.2016 / 17:01