Skip to content
Advertisement

How could I set a maxlength to an HTML “td” tag (cell)?

I have a HTML table with editable cells (every td tag in my table has “contenteditable” set to True).

The users are meant to fill the table with times in HH:mm format, so I added an onkeypress attribute which triggers a function that checks if the user is entering something other than numbers or the “:” character, and ignores it if that’s the case, like so:

HTML

<td contenteditable="true" onkeypress="return isNumberKey(event)"> </td>

Javascript

function isNumberKey(evt){
            let charCode = (evt.which) ? evt.which : event.keyCode;
            if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode!=58)
                return false;
            return true;
        }

The problem now is that users can enter more that 5 characters and write stuff like “345:678” for example.

I would like to know if its possible to limit the number of characters they can enter in the cell to 5 (just like an input tag’s “maxlength” attribute), and if it’s possible to somehow limit the users to typing two numbers, then a “:” character, then two more numbers. (Even though setting a maxlength would already be pretty nice).

I also wrote a Regex which checks that something is the HH:mm format, but I don’t think it’s useful in this case since it can only be tested after the user has typed the full five characters, right?

Here it is just in case:

const timeRegex = RegExp("^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$");

Here is the JSFiddle

Advertisement

Answer

if you already do the checking which characters a user can input into the td with javascript, so why don’t just also add the functionality for the current length and other characters to the function too ?

F.e. like this:

function isNumberKey(evt){
            let charCode = (evt.which) ? evt.which : event.keyCode;
            if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode!=58)
                return false;
                
            var currentContent = evt.target.innerHTML;
            if (currentContent.length >= 5)
                return false;
                
            if (currentContent.length === 2 && charCode !== 58)
                return false;

            return true;
        }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement