Text field extension depending on how much text it has (jquery)

How to get a text field that initially has only one line, but then when the text reaches the end of the line to add another line, and continue to do so up to five lines?

+6
source share
5 answers

Something like that:

<textarea id="foo" rows="1" cols="40"></textarea> $(function () { $("#foo").on("keyup", function () { if ($(this).attr('rows') < 5 && parseInt($(this).val().length/$(this).attr('cols')) >= $(this).attr('rows')) $(this).attr("rows", parseInt($(this).attr("rows"))+1); }); }); 

http://jsfiddle.net/Q3pPT/

edit Minor improvements for handling newline:

 $(function () { $("#foo").on("keyup", function (e) { if ($(this).attr('rows') < 5) { if ( parseInt($(this).val().length/$(this).attr('cols'))+ ($(this).val().split("\n").length-1) >= $(this).attr('rows') ) $(this).attr("rows", parseInt($(this).attr("rows"))+1); if (e.keyCode == 13) { $(this).attr("rows", parseInt($(this).attr("rows"))+1); } } }); }); 

http://jsfiddle.net/Q3pPT/2/

+1
source

I took the idea from Jake Feysel's answer, and it not only works to expand, but also to compress the text box in case of less content.

HTML

 <textarea id="foo" rows="1" cols="40"></textarea> <div id="stat"></div> 

It also displays the ideal number of lines needed according to the contents of the div divider

CSS

 ​#foo { resize:none; }​ 

This is required because once the text field has been modified using this handler, the code stops working

Js

 $(function () { $("#foo").on("keyup", function (e) { var idealRows = parseInt($(this).val().length/$(this).attr('cols'))+ ($(this).val().split("\n").length-1)+1 ; var rows = $(this).attr('rows'); // for the bugging scroll bar if(rows > 4) $('#foo').css('overflow','auto') else $('#foo').css('overflow','hidden') // for expanding and contracting if( (idealRows > rows) && (rows < 5) || (idealRows < rows) && (rows > 1)) $(this).attr("rows", idealRows); }); });​ 

Demo: http://jsfiddle.net/roopunk/xPdaP/3/

Note that he also takes care of the scroll bar that appears between keyDown and keyUp. IMO: This is a kind of audition.

Note I hope this helps! :)

+1
source

Check out the Elastic jQuery plugin: http://unwrongest.com/projects/elastic/

You can use the max-height property on your CSS in combination with the maximum length of your text box to limit it to 5 lines.

0
source

download this plugin: http://james.padolsey.com/demos/plugins/jQuery/autoresize.jquery.js

 $('textarea#comment').autoResize({ // On resize: onResize : function() { $(this).css({opacity:0.8}); }, // After resize: animateCallback : function() { $(this).css({opacity:1}); }, // Quite slow animation: animateDuration : 300, // More extra space: extraSpace : 40 }); 
0
source

Source: https://habr.com/ru/post/902690/


All Articles