2016-06-13 64 views
0

我想允许使用,以高达300字符的输入,同时我想根据用户的文本增加textarea的,如果他删除文本减少文本区域计数多行文本字符和文本区域

https://jsfiddle.net/yhqdhr3x/

<div id="divChar">300</div> 
<textarea id="txtpostSearch" class="form-control" rows="3" ></textarea> 
的增加或减少大小

jQuery代码

$('#txtpostSearch').keyup(function() {     
    var txtCharCountLength = $(this).val().length; 
    if (txtCharCountLength <= 300) { 
    var remainingChar = 300 - txtCharCountLength; 
    $("#divChar").html(remainingChar); 
    } 
}); 
+0

检查了这一点:http://stackoverflow.com/a/12269010/1267304 – DontVoteMeDown

+0

的可能的复制[简单的jQuery textarea的扩展,以适应内容(HTTP ://stackoverflow.com/questions/12268921/simple-jquery-textarea-expand-to-fit-content) – DontVoteMeDown

+0

@DontVoteMeDown:我想算的性格也 – Sri

回答

0

在你的初始化,把下面以防止出现错误(这是什么让这不到3 00个字符):

oldVal = ""; 

如果使用等宽字体,并且知道适合在一排字符的数量,每个信打的时候,你可以做到以下几点上键入每个字符....这是假设你可以在每行适合22个字符...

// save the element as variable, just to access without typing as much 
elem = document.getElementById('txtpostSearch'); 

//if the length is above 300, set it back to what the value was before 
if(elem.length > 300){ 
    elem.value = elem.value.substring(0, 300); 
} 

// the length of the contents of the textarea 
len = elem.value.length; 
// the new number of rows in the textarea 
// it is the number of rows completely filled by text, plus two 
// plus two makes room for the row currently typing in, and one more empty row 
rows = Math.floor(len/22) + 2; 
// sets the height as the number of rows in units of font size 
elem.style.height = rows + 'em'; 

//store the value in case the next length is too large 
oldVal = elem.value; 

我做了一个小提琴:https://jsfiddle.net/5w7gogqt/

这拨弄使用一个叫做ProFont(如果你没有它的字体,小提琴默认为普通等宽),无论您使用哪种操作系统或浏览器,它总是具有一定的大小。你总是可以为你的领域使用一个webfont,然后人们使用这个字体,即使他们没有它。

+0

后300 Char也允许它允许要输入文字,我不想在300字符后输入 – Sri

+0

将此添加到我的答案中 - 我忘记了这一点。 – MineAndCraft12

+0

我必须添加这个 – Sri

0

您可以使用JQuery更改文本区域的行数和列数。

要限制输入字符的数量有maxlength,但它不能在所有浏览器上始终如一地工作,作为替代方法,您可以用substring截断文本框的内容并更改文本框的值。

演示:

$('#txtpostSearch').keyup(function() { 
 
    var str = $(this).val(); 
 
    var txtCharCountLength = str.length; 
 
    
 
    if (txtCharCountLength <= 300) { 
 
    var remainingChar = 300 - txtCharCountLength; 
 
    $("#divChar").html(remainingChar); 
 
    var rows = str.split("\n"); 
 
    var cols = rows.sort(function(a, b) { 
 
     return b.length - a.length 
 
    })[0].length; 
 

 
    $(this).attr('rows', rows.length + 1); 
 
    $(this).attr('cols', cols); 
 
    } 
 
    else { 
 
    $(this).val($(this).val().substring(0, 300)); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="divChar">300</div> 
 
<textarea runat="server" class="form-control" cows="3" id="txtpostSearch"></textarea>