使用 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。
Using jQuery I would like to:
- Limit the number of lines a user can enter in a textarea to a set number
- Have a line counter appear that updates number of lines as lines are entered
- Return key or \n would count as line
$(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>
For this example lets say limit the number of lines allowed to 10.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
html:
js:
小提琴:
http://jsfiddle.net/XNCkH/17/
html:
js:
fiddle:
http://jsfiddle.net/XNCkH/17/
这是一些改进的代码。在前面的示例中,您可以粘贴具有所需更多行的文本。
HTML
JS
Here is little improved code. In previous example you could paste text with more lines that you want.
HTML
JS
对于将新值设置为状态并将其转发给 props 的 React 功能组件:
For React functional component that sets new value into state and forwards it also to props:
对于 React 粉丝来说,可能对普通 JS 事件处理程序有启发:
此示例将文本区域限制为 2 行或总共 80 个字符。
它阻止用新值更新状态,从而阻止 React 将该值添加到文本区域。
For the React fans out there, and possibly inspiration for a vanilla JS event handler:
This example limits a textarea to 2 lines or 80 characters total.
It prevents updating the state with a new value, preventing React from adding that value to the textarea.
一个很丑陋但不知何故有效的例子
指定文本区域的行
,然后
在js中
A much ugly , but somehow working example
specify rows of textarea
and then
in js