Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit character input in contenteditable used within a html table

I am currently using a html table within my web page to allow the user to input certain details. However as there is no limit on the character input the table can be stretched largely when the user types in as many characters as they wish.

I was wondering how to limit this contenteditable to prevent this from happening?

Below is a snippet of the code I am using for the table

<tr>
<td>One Off Capital</td>
<td><div contenteditable>  </div></td>
<td><div contenteditable>  </div></td>
</tr>

I have found this link below to a similar problem, however being new to jQuery and an amateur developer, I am struggling to understand the answers given and how I can use them.

Limiting Number of Characters in a ContentEditable div

like image 390
1D9C Avatar asked Sep 26 '22 19:09

1D9C


1 Answers

You can do something tricky with keypress() event handler. Prevent keypress event if content is greater than your limit by returning false

UPDATE : Add listener to paste event. Then check the content length. Also prevent drag option in order to prevent content dragging to it.

var limit = 10;
$('div[contenteditable]').keypress(function() {
  return this.innerHTML.length < limit;
}).on({
  'paste': function(e) {
    var len = this.innerHTML.length,
      cp = e.originalEvent.clipboardData.getData('text');
    if (len < limit)
      this.innerHTML += cp.substring(0, limit - len);
    return false;
  },
  'drop': function(e) {
    e.preventDefault();
    e.stopPropagation();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<tr>
  <td>One Off Capital</td>
  <td>
    <div contenteditable></div>
  </td>
  <td>
    <div contenteditable></div>
  </td>
</tr>
like image 107
Pranav C Balan Avatar answered Oct 03 '22 21:10

Pranav C Balan