Javascript

Buchstabenzähler in Textbox implementieren

Mit JavaScript die Eingabe in einer Textarea begrenzen

Eine Interaktion per HTML-Formular mit dem Besucher einer Web-Seite ist inzwischen Standard. Neben einem Kontaktformular, dessen ausgefüllter Inhalt meist per eMail an den Web-Betreiber verschickt wird, kommen Kommentare zu bestimmten Artikeln oder Beiträgen immer mehr in Mode, denn schließlich sorgt das Feedback der Besucher für eine bessere Qualität der Inhalte. Solche Kommentare werden zumeist in Datenbanken gespeichert, um sie später auch anderen Lesern eines Beitrages anzeigen zu können.

Beim Speichern eines solchen Kommentars steht der Entwickler der Seite meist vor einem Problem: wie groß soll das Tabellenfeld werden in das der Kommentar gespeichert wird, denn schließlich kann eine Textbox eines HTML-Formulars (Textarea) sehr viel Text aufnehmen. Alles zu speichern, kann bei einer fast immer begrenzten Datenbankgröße schnell zu einem Problem werden. Der Ansatz den Besucher so viel Text eingeben zu lassen wie er möchte und den Kommentar ab einer gewissen Länge abzuschneiden, um die Datenbank nicht zu groß werden zu lassen, ist nicht besonders geschickt und schreckt eher ab.

Das Beste wäre es, jedem Benutzer nur einen bestimmte Anzahl an Zeichen für seinen Kommentar zur Verfügung zu stellen, d.h. die Eingabe in die Textarea zu limitieren und dem Besucher während der Eingabe anzuzeigen wieviele Zeichen er noch eingeben kann. Dies mit ein wenig Javascript-Code zu bewerkstelligen ist Gegenstand dieses Artikels.

Um die Vorgehensweise zu verdeutlichen, brauchen wir zunächst ein kleines HTML-Formular:

<form method="POST" action="...">
  <textarea name="txtText" id="txtText" rows="4" cols="30"></textarea>
  <br>
  <input type="submit" value="Absenden" name="btnSend">
</form>

Zu beachten ist, dass die textarea einen Namen und eine ID mit gleichem Inhalt trägt. Somit werden von vorneherein Schwierigkeiten mit älteren Browsern vermieden.

Das action-Attribut des Formulars muss entsprechend den eigenen Gegebenheiten angepasst werden. Zumeist wird hier eine ASP- oder PHP-Seite aufgerufen, die den Inhalt des Formulars in die Datenbank schreibt.

Als nächstes wird im head des HTML-Dokuments eine Javascript-Funktion benötigt, die während der Eingabe in die Textbox einen globalen Zähler mitführt und im Falle einer Überschreitung der gewünschten Buchstabenanzahl weitere Eingaben unterdrückt:

<script type="text/javascript">

// globale Zählervariable
var charsToGo;

function charCounter(charInputSrcName, maxCharCount, outputTargetName) {

   // Zugriffsvariablen festlegen
   var charInputSrc = document.getElementById(charInputSrcName);
   var outputTargetSrc = document.getElementById(outputTargetName);

   if (charInputSrc != null) {
      // Länge des Feldinhaltes prüfen
      if (charInputSrc.value.length <= maxCharCount) {
         // Anzahl Restzeichen berechnen und Zeichenanzeige aktualisieren
         charsToGo = maxCharCount - charInputSrc.value.length;
         outputTargetSrc.innerHTML = '(' + charsToGo + '&nbsp;Zeichen)';
      }
      else
         // Eingegebenes Zeichen wieder abschneiden
         charInputSrc.value = charInputSrc.value.substring(0, maxCharCount);
         charsToGo = maxCharCount - charInputSrc.value.length;
      }
}

</script>

Die Funktion hat drei Parameter. Der Reihenfolge nach sind dies der Name der Textarea, die Anzahl der maximal zulässigen Zeichen und der Name des HTML-Objekts, das die Anzeige der noch verfügbaren Zeichen übernimmt. In Zeile 17 wird letzteres mit dem besagten Wert über die Eigenschaft innerHTML bestückt.

Da der Aufruf der Funktion bei der Eingabe von Text in der Textarea stattfinden soll, muss die HTML-Deklaration erweitern werden. Hierzu verwenden wir die drei Ereignisse onKeyDown, onKeyUp und onChange, um auf alle Fälle sicherzustellen jede Eingabe mitzubekommen.

<textarea name="txtText" id="txtText" rows="4" cols="30"
   onKeyDown="charCounter('txtText', 500, 'charCount');"
   onKeyUp="charCounter('txtText', 500, 'charCount');"
   onChange="charCounter('txtText', 500, 'charCount');"></textarea>

Nun wird die Eingabe bereits auf 500 Zeichen beschränkt. Fehlt nur noch die Ausgabe der verfügbaren Zeichen. Diese implementieren wir über eine weitere Javascript-Funktion, die das von uns gewünschte HTML-Element, hier ein span-Element, direkt auf der Seite ausgibt. Um sicherzustellen, dass bei einem etwaigen manuellen Reload der Seite durch den Benutzer auch der richtige Wert angezeigt wird, findet hier zudem noch eine Überprüfung der globalen Zählervariablen statt.

function counterOutput(charInputSrcName, maxCharCount, outputTargetName)
{
   // Zugriffsvariablen festlegen
   var charInputSrc = document.getElementById(charInputSrcName);

   // globale Variable prüfen
   if (charsToGo == null) {
      // Ausgabewert berechnen
      charsCount = maxCharCount - charInputSrc.value.length; }
   else
      // Ausgabefeld initialisieren
      charsCount = charsToGo;
         document.write('<span name=\"'
            + outputTargetName + '\" id=\"' + outputTargetName +'\">('
            + charsCount + '&nbsp;Zeichen)</span>')
}

Um die eigentliche Ausgabe kümmert sich ein kurzes Javascript-Statement an der Stelle im HTML-Code wo die Anzeige stattfinden soll. Unser HTML-Formular von oben könnte dann z.B. so aussehen:

<form method="POST" action="...">
  <textarea name="txtText" id="txtText" rows="4" cols="30"
      onKeyDown="charCounter('txtText', 500, 'charCount');"
      onKeyUp="charCounter('txtText', 500, 'charCount');"
      onChange="charCounter('txtText', 500, 'charCount');"></textarea>
  <br>
   <script language="JavaScript" type="text/javascript">
      counterOutput('txtText', 500, 'charCount');
   </script>
   <br>
   <input type="submit" value="Absenden" name="btnSend">
</form>
 

Hier ein Beispiel, wie die Eingabebegrenzung funktioniert:


kick it on dotnet-kicks.de AddThis Trackback-Url...

210 Kommentare bislang...

  • Ce que les Britanniques Gree, Gwen, <a href="http://www.bottesenligne.net/">ugg france</a> Dantley, Chris Mullin, <a href="http://www.sacamain4chanel.com/">sacs chanel</a> Richmond, Hardaway, Hill, Latrell Weir, <a href="http://www.moncler4soldesfr.net/">doudoune longue femme</a> Houston, Jerry Stackhouse, Vince Carter, Tracy <a href="http://www.bottesenligne.net/">ugg bottes</a> McGrady, Finley, <a href="http://www.niketnrequinpaschere.net/">requin tn pas cher</a> s'accrochant à une cuisse géante <a href="http://www.timberlandpascherfr.com/timberland-c-133.html">timberland chaussure</a> avant que le Dr J, <a href="http://www.bottesenligne.net/">ugg</a> planeur, Pierce <a href="http://www.niketnrequinpaschere.net/">requin tn</a> (microblogging), Ray - Ray Allen, Peja loin Weber, <a href="http://www.timberlandpascherfr.com/timberland-c-133.html">chaussure timberland</a> Michael - <a href="http://www.chaussuresairmaxfr.com/">chaussure nike pas cher</a> Reed, <a href="http://www.niketnrequinpaschere.net/">nike requin</a> Joe - Johnson, Andre Iguodala et la date <a href="http://www.timberlandpascherfr.com/timberland-c-133.html">timberland pas cher</a> de James, <a href="http://www.chaussuresairmaxfr.com/">chaussure pas cher</a> Anthony <a href="http://www.uggsbottes.org/">Ugg</a> (microblogging) ... Si les noms et les exploits <a href="http://www.chaussuresnikepascher4fr.com/">nike chaussure pas cher</a> de l'échec de <a href="http://www.timberland-pas-cher1.com/">timberland</a> la liste de toutes redevances assez de tricher <a href="http://www.nikeshoxrivalry4fr.com/">shox rival</a> milliers de pièces. Et <a href="http://www.chaussuresnikepascher4fr.com/">chaussure nike homme</a> nous <a href="http://www.niketnpascher4fr.com/">chaussure tn pas cher</a> savons tous, même avec un genou parfait, <a href="http://www.nikeshoxrivalry4fr.com/">nike shox pas cher</a> Roy n'a pas une <a href="http://www.chaussuresnikepascher4fr.com/">chaussures nike femme</a> capacité suffisante <a href="http://www.niketnpascher4fr.com/">nike tn pas chere</a> de la longue liste de <a href="http://www.nikeshoxrivalry4fr.com/">nike shox nz</a> se démarquer, a sauté <a href="http://www.chaussuresnikepascher4fr.com/">chaussure pas cher femme</a> dans le <a href="http://www.niketnpascher4fr.com/">nike tn foot locker</a> Jourdain, Kobe Bryant dans <a href="http://www.nikeshoxrivalry4fr.com/">nike shox rivalry</a> ce fichier. Par conséquent, <a href="http://www.ugg4siteofficiel.com/">ugg boots france</a> comme un effet direct <a href="http://www.niketnpascher4fr.com/">chaussures tn</a> admettre: Si vous n'avez <a href="http://www.nikeshoxrivalry4fr.com/">shox</a> pas l'aile supérieure <a href="http://www.doudounemonclerfemme4pascher.net/">moncler femme</a> sur la planète, <a href="http://www.sacamain4chanel.com/">sac chanel prix</a> plus une variété de facteurs <a href="http://www.uggsaustralia4pascher.com/">ugg australia en ligne</a> favorables, la <a href="http://www.doudounemonclerfemme4pascher.net/">doudoune femme</a> meilleure <a href="http://www.sacamain4chanel.com/">sac chanel pas cher</a> fa?on de construire une autre équipe, <a href="http://www.uggsaustr
    210
    Dream_T : Mittwoch, 18. Januar 2012 09:50
  • Thank you for taking the time to write this article. You really know what you're writing about and it's clearly evident that you take the time to do some quality research to deliver quality information. Your insights are greatly appreciated. Thanks and more power to you.
    209
    My free credit report : Mittwoch, 18. Januar 2012 03:38
  • If you a football fans,<a href="http://www.cheapnflhotjersey.com" title="Nfl Jerseys">Nfl Jerseys</a> you must be worry about it for your favor players after knowing the news.<a href="http://www.cheapnflhotjersey.com" title="Nfl Jersey Sale">Nfl Jersey Sale</a> At this time you are sure to cheer and <a href="http://www.cheapnflhotjersey.com" title="cheap nfl jerseys">cheap nfl jerseys</a> encourage for them by wearing nfl jerseys to support of them.<a href="http://www.cheapnflhotjersey.com" title="mens nfl jerseys">mens nfl jerseys</a> No matter you wear cheap nfl jerseys,<a href="http://www.cheapnflhotjersey.com" title="charles woodson jersey">charles woodson jersey</a> or replica nfl jerseys brought fromwholesale nfl jerseys shops.<a href="http://www.cheapnflhotjersey.com" title="authentic nfl jerseys">authentic nfl jerseys</a> it all display your support for them.<a href="http://www.cheapnflhotjersey.com" title="authentic nfl jerseys cheap">authentic nfl jerseys cheap</a> If you want to buy good nfl jerseys but have no money,<a href="http://www.cheapnflhotjersey.com" title="discount nfl jerseys">discount nfl jerseys</a> you can visit shopnfljersey.org online shops and get <a href="http://www.cheapnflhotjersey.com" title="football nfl jerseys">football nfl jerseys</a> to know whether or not nfl jerseys is affortable for everyone like you there.<a href="http://www.hotfootballjersey.com" title="cheap football jersey">cheap football jersey</a> You put into practice in order to encourage your favorite football team.<a href="http://www.hotfootballjersey.com" title="jerseys online store">jerseys online store</a> however, it doesn't mean which you can't buy these replica nfl jerseys.<a href="http://www.hotfootballjersey.com" title="football jerseys">football jerseys </a> on the reverse.<a href="http://www.hotfootballjersey.com" title="football jerseys for kids">football jerseys for kids</a> You should spend your spare time surfing for it by way of <a href="http://www.hotfootballjersey.com" title="authentic football jersey">authentic football jersey</a> the internet you can discover some elements that <a href="http://www.hotfootballjersey.com" title="where to buy football jerseys">where to buy football jerseys</a> will make sure you wholesale nfl jerseys whose cost is reasonable.<a href="http://www.hotfootballjersey.com" title="Nike football jersey">Nike football jersey</a> The internet could be the most effective chanel to look for these nfl jerseys.<a href="http://www.hotfootballjersey.com" title="best place to buy football jerseys">best place to buy football jerseys</a> So what it really is feasible to only need undertake lie in <a href="http://www.hotfootballjersey.com" title="Chelsea jerseys">Chelsea jerseys</a> product brand you'll like buying by right of search engines like Google,<a href="http://www.hotfootballjersey.com" title="Manchester jerseys">Manchester jerseys</a> yahoo,bing that are leading.<a href="http://www.cheapnbajersey.com" title="cheap nba jerseys">cheap nba jerseys </a> You only type the keywords that are relatve to All Star NBA Jerseys which you want,<a href="http://www.cheapnbajersey.com" title="nba jerseys">nba jerseys </a> quite a few outcomes will show on computer screen within the twinking of the eyesight.Of course,<a href=&qu
    208
    longyuelt : Dienstag, 17. Januar 2012 02:31
  • Numerous stores contain fun costumes <a href="http://www.smallworld-us.com" title="Cosplay Costumes">Cosplay Costumes</a> for dressing up either for Halloween or just for fun. Most <a href="http://www.smallworld-us.com" title="Wholesale Cell Phones">Wholesale Cell Phones</a> of these stores are aimed at <a href="http://www.smallworld-us.com" title="Computer Accessories">Computer Accessories</a> teenagers and young adults, <a href="http://www.smallworld-us.com" title="Tiffany Jewelry">Tiffany Jewelry</a> who are more open to wearing costumes <a href="http://www.smallworld-us.com" title="soccer jerseys">soccer jerseys</a> and also enjoy standing out due to their clothes. <a href="http://www.smallworld-us.com" title="NBA jerseys">NBA jerseys</a> It is important for many young people to <a href="http://www.smallworld-us.com" title="Monster Headphones">Monster Headphones</a> make a statement or tell you about their personality through their <a href="http://www.smallworld-us.com" title="Monster Headphones dr. dre">Monster Headphones dr. dre</a> costumes.This is why cosplay has become so popular. <a href="http://www.smallworld-us.com" title="cheap wedding dresses">cheap wedding dresses</a> If you are considering to do cosplay the most important part is <a href="http://www.smallworld-us.com" title="discount wedding dresses">discount wedding dresses</a> deciding what character to be. Think about what characters <a href="http://www.smallworld-us.com" title="zentai">zentai</a> you love from all the common cosplay mediums <a href="http://www.smallworld-us.com" title="zentai suits">zentai suits</a> such as video games, manga, anime, or movies.

    If you can think of a wonderful <a href="http://www.smallworld-us.com" title="Spiderman Lycra Spandex Zentai Suit">Spiderman Lycra Spandex Zentai Suit</a> costume that a character has worn that you absolutely loved that is another great choice for cosplay.<a href="http://www.smallworld-us.com" title="Cheap Zentai Suits">Cheap Zentai Suits</a> When doing cosplay the best route is to create your own costume, <a href="http://www.smallworld-us.com" title="finger shoes">finger shoes</a> this means just the basic costume. <a href="http://www.smallworld-us.com" title="5 finger">5 finger</a> It is important because the costume will fit you better and can be exactly <a href="http://www.smallworld-us.com" title="5 finger shoes">5 finger shoes</a> what you want if you create <a href="http://www.smallworld-us.com" title="cycling">cycling</a> it yourself. However, <a href="http://www.beautyhu.com" title="Tiffany Bracelet">Tiffany Bracelet</a> it is fine to use some bought materials for <a href="http://www.beautyhu.com" title="Tiffany Earrings">Tiffany Earrings</a> certain pieces like jewelry a <a href="http://www.beautyhu.com" title="Tiffany rings">Tiffany rings</a> character always wears or maybe a symbol. <a href="http://www.beautyhu.com" title="Tiffany jewelry">Tiffany jewelry</a> Naruto cosplay costumes <a href="http://www.beautyhu.com" title="Tiffany Necklace">Tiffany Necklace</a> should be exact for example, <a href="http://www.beautyhu.com" title="tiffany and co">tiffany and co</a> make sure to get contacts if cosplaying as Sasuke. Here is some g
    207
    kk : Montag, 16. Januar 2012 05:42
  • Valuable information ..I am delighted to read this article..thank you for giving us this useful information. Great walk-through. I value this post.
    206
    Microsoft Outlook : Freitag, 6. Januar 2012 02:19

Dein Kommentar hierzu...


Kommentar-Feed für diesen Beitrag
Gravatare werden unterstützt .:. eMail-Adressen werden nicht veröffentlicht
 

RSS-Feed

Die URL des Standard-Newsfeed von zerbit.de lautet:

http://www.zerbit.de/rssfeed.aspx

Login


 

 

Statistik



kürzlich kommentiert

Artikel 48

  • Datum: 13.11.2005
    Kategorie: Javascript
    Zugriffe: 10.236
    Kommentare: 210
    Trackbacks: 0

Letzte Beiträge

Kategorien

Buttons & More

Blog-Roll

Banner Piraten-Partei