IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JavaScript Discussion :

Limite Textarea, Ligne et Nombre de caractères par ligne


Sujet :

JavaScript

  1. #1
    Membre averti
    Homme Profil pro
    Bientôt retraité
    Inscrit en
    Juillet 2005
    Messages
    312
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 67
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Bientôt retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juillet 2005
    Messages : 312
    Points : 385
    Points
    385
    Par défaut Limite Textarea, Ligne et Nombre de caractères par ligne
    Bonjour,

    je tourne en bourique.
    J'ai une zone Textarea. Je voudrais limiter le nomde de caractères par lignes et le nombre de lignes. Evidement, pour faire simple, l'utilisateur va parfois faire un retour à la ligne et parfois non, donc le retour se fera en automatique.
    Est-ce possible? Existe-t-il un type de zone le permettant?

    Par avance merci.

  2. #2
    Rédacteur/Modérateur

    Avatar de SpaceFrog
    Homme Profil pro
    Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Inscrit en
    Mars 2002
    Messages
    39 640
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 74
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2002
    Messages : 39 640
    Points : 66 663
    Points
    66 663
    Billets dans le blog
    1
    Par défaut
    cols rows et maxlength ?

  3. #3
    Membre averti
    Profil pro
    Inscrit en
    Novembre 2010
    Messages
    207
    Détails du profil
    Informations personnelles :
    Localisation : France, Indre et Loire (Centre)

    Informations forums :
    Inscription : Novembre 2010
    Messages : 207
    Points : 344
    Points
    344

  4. #4
    Membre averti
    Homme Profil pro
    Bientôt retraité
    Inscrit en
    Juillet 2005
    Messages
    312
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 67
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Bientôt retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juillet 2005
    Messages : 312
    Points : 385
    Points
    385
    Par défaut
    Bonjour,

    Aucune des solutions proposées correspondait au besoin spécifique mais elles m'ont permis d'avoir les pistes pour la solution. De plus, ce n'est pas moi quil lait trouvée mais un de mes collègues. Je mets ici le source en espérant qu'elle pourra servir à d'autres.
    Dans tous les cas, merci pour vos pistes.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head>
    	<meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
    	<title>textarea</title>
    	<!--styles START--> 
    	<style> 
    	html {
    		height: 100%; /* Fix height to 100% for IE! */
    		font-size: 100.01%; /* Correct font related browserbugs in IE, Opera and Safari. */
    	}
    	body {
    		height: 100%; /* Fix height to 100% for IE! */
    		font-family: Times,"Time New Roman",serif;
    		font-size: 16px;
    		background: #554A46;
    	}
    	a {
    		text-decoration: none;
    		font-weight: 700;
    		color: #554A46;	
    	}
    	a:hover {
    		color: #D22527;	
    	}
    	fieldset {
    		padding: 1em;
    		color: #554A46;
    		background: #FFFCFC;
    		border: 1px solid #D22527;
    	}
    	legend {
    		display: none;
    	}
    	#info {
    		color: #D22527;
    		font-size: .8em;
    	}
    	label {
    		text-transform: lowercase;
    		font-variant: small-caps;
    		line-height: 1.6em;
    	}
    	</style>
     
    	<!--styles END--> 
     
    	<!--javascript START--> 
    	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script> 
    	<script type="text/javascript"> 
    	/*
    	 * TextLimit - jQuery plugin for counting and limiting characters and lines for textarea fields
    	 * 
    	 * Example: jQuery("Textarea").textlimit('span.counter',256,10)
    	 */
    	jQuery.fn.textlimit=function(counter_el, thelimit_char, thelimit_line, speed) {
    		var charDelSpeed = speed || 15;
     
    		var that = this[0];
    		var t = this;
    		var cut = 0;
    		var count_lines = countLines(t);
    		updateCounter();
     
    		function updateCounter(){
    			jQuery(counter_el).text('left '+(thelimit_char - that.value.length)+' chars and '+(thelimit_line - count_lines)+' lines');
    		};
     
    		function countLines(ta){
    			// Get the textarea value
    			var value = ta.val();
     
    			var options = {
    				recalculateCharWidth : false,
    				chars : "",
    				fontAttrs : ["font-family", "font-size", "text-decoration", "font-style", "font-weight"]
    			};
    			var masterCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    			var counter;
     
    			// Build a random collection of characters
    			masterCharacters += ".,?!-+;:'\"";
    			for (counter = 1; counter <= 12; counter++)
    				options.chars += masterCharacters[(Math.floor(Math.random() * masterCharacters.length))];
     
    			// Decode chars
    			if (!$.isArray(options.chars))
    				options.chars = options.chars.split("");
     
    			// Generate a span after the textarea with a random ID
    			var id = "";
    			for (counter = 1; counter <= 10; counter++)
    				id += (Math.floor(Math.random() * 10) + 1);
     
    			ta.after("<span id='s" + id + "'></span>");
    			var span = $("#s" + id);
     
    			// Hide the span
    			span.hide();
     
    			// Apply the font properties of the textarea to the span class
    			$.each(options.fontAttrs, function(i, v){
    				span.css(v, ta.css(v));
    			});
     
    			// Get the number of lines
    			var lines = value.split("\n");
    			var linesLen = lines.length;
     
    			var averageWidth;
     
    			// Check if the textarea has a cached version of the average character width
    			if (options.recalculateCharWidth || ta.data("average_char") == null) {
    				// Get a pretty good estimation of the width of a character in the textarea. To get a better average, add more characters and symbols to this list
    				var chars = options.chars;
     
    				var charLen = chars.length;
    				var totalWidth = 0;
     
    				$.each(chars, function(i, v){
    				span.text(v);
    				totalWidth += span.width();
    				});
     
    				// Store average width on textarea
    				ta.data("average_char", Math.ceil(totalWidth / charLen));
    			}
     
    			averageWidth = ta.data("average_char");
     
    			// We are done with the span, so kill it
    			span.remove();
     
    			// Determine missing width (from padding, margins, borders, etc); this is what we will add to each line width
    			var missingWidth = (ta.outerWidth() - ta.width()) * 2;
     
    			// Calculate the number of lines that occupy more than one line
    			var lineWidth;
    			var wrappingCount = 0;
     
    			$.each(lines, function(i, v){
    				// Calculate width of line
    				lineWidth = ((v.length + 1) * averageWidth) + missingWidth;
    				// Check if the line is wrapped
    				if (lineWidth >= ta.outerWidth()){
    					// Calculate number of times the line wraps
    					var wrapCount = Math.floor(lineWidth / ta.outerWidth());
    					wrappingCount += wrapCount;
    				}
    			});
     
    			return (linesLen + wrappingCount);
    		};
     
    		this.keypress (function(e){ 
    			if( this.value.length >= thelimit_char && e.charCode != '0') {
    				e.preventDefault();
    			}
    		}).keyup (function(e){
    			count_lines = countLines(t);
    			updateCounter();
    			if( count_lines >= thelimit_line ){
    				var init = setInterval( 
    						function(){
    							//console.log("count:"+count_lines+" ; limit:"+thelimit_line);
    							if( count_lines <= thelimit_line){ 
    								init = clearInterval(init); 
    								updateCounter();
    							}
    							else{ 
    								count_lines = count_lines-1;
    								that.value = that.value.substring(0,that.value.length-2);
    								jQuery(counter_el).text('trimming line...  '+(thelimit_line - count_lines));
    							};
    						} ,charDelSpeed 
    					);
    			}
    			else if( this.value.length >= thelimit_char ){
    				// first, trim the text a bit so the char trimming won't take forever
    				that.value = that.value.substr(0,thelimit_char+100);
    				var init = setInterval( 
    						function(){ 
    							if( that.value.length <= thelimit_char){ 
    								init = clearInterval(init); 
    								updateCounter();
    							}
    							else{ 
    								that.value = that.value.substring(0,that.value.length-2); 
    								jQuery(counter_el).text('trimming char...  '+(thelimit_char - that.value.length));
    							};
    						} ,charDelSpeed 
    					);
    			}
    		});
    	};
     
    	$(function(){ 
    		jQuery("#entry").textlimit('#counter',60,3);
    		jQuery("#entry2").textlimit('#counter2',60,3);
    	});
    	</script> 
    	<!--javascript END--> 
    </head> 
     
    <body> 
     
    	<!--form START--> 
    	<form> 
    		<fieldset> 
    			<label for="entry">Enter your text</label> <span id="counter"></span><br /> 
    			<textarea id="entry" cols="20" rows="5" wrap="soft" style="white-space: wrap;"></textarea> 
    			<br><br>
    			<label for="entry">Enter your text</label> <span id="counter2"></span><br /> 
    			<textarea id="entry2" cols="20" rows="5" wrap="soft" style="white-space: wrap;"></textarea> 
    		</fieldset> 
    	</form> 
    	<!--form END--> 
    </body> 
    </html>

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. GtkTreeView limiter le nombre de caractère par ligne
    Par zephyrin_damortien dans le forum GTK+ avec C & C++
    Réponses: 1
    Dernier message: 28/03/2009, 11h39
  2. [CKEditor] limiter le nombre de caractères par ligne
    Par janclod dans le forum Bibliothèques & Frameworks
    Réponses: 2
    Dernier message: 29/09/2008, 16h42
  3. [JTextArea] Limiter nombre de caractères par lignes
    Par doudine dans le forum AWT/Swing
    Réponses: 2
    Dernier message: 17/02/2006, 17h26
  4. Limiter le nombre de caractère par ligne d'un textarea
    Par rantanplan08 dans le forum Général JavaScript
    Réponses: 12
    Dernier message: 04/01/2006, 19h31
  5. nombre de caractères par ligne à l'affichage
    Par trotters213 dans le forum Oracle
    Réponses: 3
    Dernier message: 03/11/2005, 09h51

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo