ion icon indicating copy to clipboard operation
ion copied to clipboard

Add Character Counter to Text Fields

Open naitian opened this issue 7 years ago • 4 comments

This would apply to text fields with a character limit (e.g. the poll description).

naitian avatar Jul 14 '17 15:07 naitian

To do this, one would need to either:

  1. Create a new class right above django.forms.ModelForm that overrides as_table to include a character counter when the, or
  2. Create a new class above django.forms.CharField and django.forms.TextField to, when initted, add a character counter to its widget.

1 would be slightly easier to implement, just import that class from utils or something instead of the default class, but 2 would be more effictive yet "dirtier" (and harder) because it would require monkey-patching the classes for django to use the new ones internally.

Which one should we go with, or am I missing a better option?

duvallj avatar Jul 26 '17 23:07 duvallj

Since we already have self.fields["description"].widget = forms.Textarea() here, we can just change that to something like shown below and create the counter client-side using Javascript. It would still be validated server side.

class Meta:
    model = Poll
    exclude = []  # type: List[str]
    widgets = {
            'name': forms.Textarea(attrs={"data-counter": 400),
     }

ovkulkarni avatar Jul 27 '17 15:07 ovkulkarni

My issue with that solution is that is would require patching widgets for every class that requires a character counter. That may not be a bad thing though (do we want counters everywhere?).

duvallj avatar Jul 27 '17 20:07 duvallj

This would probably only apply to things that already use a Textarea widget, so most of the code would already be there. I was looking for a dynamic way to set the length but I couldn't find one. I'll see if I can find something though

ovkulkarni avatar Jul 27 '17 21:07 ovkulkarni