2016-06-13 59 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>