计算Textarea字符并增加或减小TextArea的大小

时间:2016-06-13 18:10:28

标签: javascript jquery

我想允许用户同时输入最多300个字符。如果他删除文本,我想根据用户文本增加textarea,减少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);
    }
});

2 个答案:

答案 0 :(得分:0)

在初始化时,请使用以下内容以防止错误(这是为了使其低于300个字符):

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为您的字段,然后人们使用该字体即使他们没有它。

答案 1 :(得分: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>