Good way to determine max characters to allow in user generated area on a web page

73 Views Asked by At

I'm working on a coupon app and it has an area where business owners can enter a short "tag line" for what the coupon is for. For example:

  • 10% off one entree!
  • $5 off
  • 2 for 1 sake before 7PM
  • 15 free flapjacks if your name is Gary

Again, this is user generated. It will show up on a screen their customers can see. I'd like it to display on one line within a certain amount of pixels. It will be in Arial.

What is the best way to determine the max amount of characters to allow them to include so that it doesn't take up extra lines or overflow, considering lots of browsers...?

1

There are 1 best solutions below

3
On

If you know the font, font-size, and total width of the one line then you could just do a trial and error calculation (that is, enter characters until the end of the line).

Once you know that, you can check for the total # of characters on keyup and alert if that amount is reached.

For instance, as an example only, let's say you choose Arial 14px and you've tested it to see that 10 characters is about all that one line can hold. Then you can add something like this

$('textarea').keyup(function(){
    if($(this).val().length == 10){
        alert('You\'ve reached the limit');
    }
});

Working Example: http://jsfiddle.net/uGDKn/