Ivan Ivanov
Ivan Ivanov

Reputation: 525

break-word to next line td in html table jquery

I have a table with fixed count of td and tr. Rows and cols have fixed width and height. Every td has input type="text" inside. How can I move to next tr the text, which does not fit in td length?

Example table:

<html>
  <body>
    <table style="width:100px">
      <tr style="height:12px">
        <td style="width=50px"><input type="text" style="width:100%" value="12 34 56 44"></td>
        <td style="width=50px"><input type="text" style="width:100%" value="786 5"></td>
      </tr>
      <tr>
        <td style="width=50px"><input type="text" style="width:100%" value=""></td>
        <td style="width=50px"><input type="text" style="width:100%" value=""></td>
      </tr>
    </table>
  </body>
</html>

There are values of top-left input dont' fit in the length of the top-left td.

How can I penetrate values from top-left input to the next cell input below, which not fit in length of the top-left td using jquery ?

Here possible result:

<html>
  <body>
    <table style="width:100px">
      <tr style="height:12px">
        <td style="width=50px"><input type="text" style="width:100%" value="12 34"></td>
        <td style="width=50px"><input type="text" style="width:100%" value="786 5"></td>
      </tr>
      <tr>
        <td style="width=50px"><input type="text" style="width:100%" value="56 44"></td>
        <td style="width=50px"><input type="text" style="width:100%" value=""></td>
      </tr>
    </table>
  </body>
</html>

Upvotes: 0

Views: 613

Answers (1)

alireza yazdandoost
alireza yazdandoost

Reputation: 774

you can use scrollWidth to check if the text has overflown

here is the code snippet. just notice that I added two Ids to two inputs just for simplicity, you can remove them and change jquery code easily if you want.

while($('#in')[0].scrollWidth > $('#in').innerWidth()){
  var inputText = $('#in').val();
  var last = inputText.substr(inputText.length - 1);
  $('#in').val(inputText.slice(0,-1));
  $('#out').val($('#out').val() +''+ last);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<html>
  <body>
    <table style="width:100px">
      <tr style="height:12px">
        <td style="width=50px"><input type="text" id="in" style="width:100%" value="12 34 56 44"></td>
        <td style="width=50px"><input type="text" style="width:100%" value="786 5"></td>
      </tr>
      <tr>
        <td style="width=50px"><input type="text" id="out" style="width:100%" value=""></td>
        <td style="width=50px"><input type="text" style="width:100%" value=""></td>
      </tr>
    </table>
  </body>
</html>

Upvotes: 1

Related Questions