Di seguito riportiamo uno script utile da utilizzare nel caso in cui si voglia impostare un limite massimo visibile delle parole da inserire in una semplice textarea. Lo script visualizza ad ogni parola inserita nella textarea il relativo conteggio rimanente.
Di seguito un esempio della funzione completo anche del codice HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script type="text/javascript"> /** * jQuery.textareaCounter * Version 1.0 * Copyright (c) 2011 c.bavota - http://bavotasan.com * Dual licensed under MIT and GPL. * Date: 10/20/2011 **/ (function($){ $.fn.textareaCounter = function(options) { // setting the defaults // $("textarea").textareaCounter({ limit: 100 }); var defaults = { limit: 100 }; var options = $.extend(defaults, options); // and the plugin begins return this.each(function() { var obj, text, wordcount, limited; obj = $(this); obj.after('<span style="font-size: 11px; clear: both; margin-top: 3px; display: block;" id="counter-text">Max. '+options.limit+' parole</span>'); obj.keyup(function() { text = obj.val(); if(text === "") { wordcount = 0; } else { wordcount = $.trim(text).split(" ").length; } if(wordcount > options.limit) { $("#counter-text").html('<span style="color: #DD0000;">0 parole rimanenti</span>'); limited = $.trim(text).split(" ", options.limit); limited = limited.join(" "); $(this).val(limited); } else { $("#counter-text").html((options.limit - wordcount)+' parole rimanenti'); } }); }); }; })(jQuery); </script> </head> <body> <textarea rows="15" cols="50"></textarea> <script type="text/javascript"> $("textarea").textareaCounter(); </script> </body> </html> |
Il limite impostato di default ?? di 100 parole ma potete modificarlo a piacimento cambiando il relativo valore specificato nella funzione alla voce limit. Cos?? ?? come si presenta la funzione in azione:
Inoltre, nella funzione sopra, ho sostituito le parole in inglese visibili nel conteggio (words left) con i termini equivalenti in italiano.
Download Sito Web | Autore