限制textarea中的行数并使用jQuery显示行数

我想使用jQuery:


将用户可以在文本区域中输入的行数限制为设置的数字

使行计数器出现,以在输入行时更新行数

回车键或/ n将计为行

感谢任何可以帮助的人!


$(document).ready(function(){

  $('#countMe').keydown(function(event) {

    // If number of lines is > X (specified by me) return false

    // Count number of lines/update as user enters them turn red if over limit.


  });   

});



<form class="lineCount">

  <textarea id="countMe" cols="30" rows="5"></textarea><br>

  <input type="submit" value="Test Me">

</form>


<div class="theCount">Lines used = X (updates as lines entered)<div>

对于此示例,可以说将允许的行数限制为10。


谢谢大家!


人到中年有点甜
浏览 1667回答 3
3回答

jeck猫

这是很少的改进代码。在前面的示例中,您可以粘贴带有更多行的文本。的HTML<textarea data-max="10"></textarea><div class="theCount">Lines used: <span id="linesUsed">0</span></div>JSjQuery('document').on('keyup change', 'textarea', function(e){&nbsp; &nbsp; &nbsp; &nbsp; var maxLines = jQuery(this).attr('data-max');&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; newLines = $(this).val().split("\n").length;&nbsp; &nbsp; &nbsp; &nbsp; console.log($(this).val().split("\n"));&nbsp; &nbsp; &nbsp; &nbsp; if(newLines >= maxLines) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lines = $(this).val().split("\n").slice(0, maxLines);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var newValue = lines.join("\n");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(this).val(newValue);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#linesUsed").html(newLines);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });

喵喵时光机

一个非常丑陋但以某种方式起作用的示例指定了textarea行<textarea rows="3"></textarea>然后在js中&nbsp; &nbsp;$("textarea").on('keydown keypress keyup',function(e){&nbsp; &nbsp; &nbsp; &nbsp;if(e.keyCode == 8 || e.keyCode == 46){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return true;&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;var maxRowCount = $(this).attr("rows") || 2;&nbsp; &nbsp; &nbsp; &nbsp; var lineCount = $(this).val().split('\n').length;&nbsp; &nbsp; &nbsp; &nbsp; if(e.keyCode == 13){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(lineCount == maxRowCount){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; var jsElement = $(this)[0];&nbsp; &nbsp; &nbsp; &nbsp; if(jsElement.clientHeight < jsElement.scrollHeight){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var text = $(this).val();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; text= text.slice(0, -1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(this).val(text);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP