我正在使用下面的代码来检测HTML textarea
$('textarea').keypress(function(e) {
var text = $(".writeLines").val();
var lines = text.split(/\r|\r\n|\n/);
var count = lines.length;
if (count > 5) {
return false
}
});
这很好用,但是人们似乎一直在通过使用空白行或其中仅包含空格的行来围绕计数检查器寻找方法。对于我们的系统,要求在每行上都有内容,什么是完成此操作的好方法?
我知道这可以被用户绕开,所以也许我们应该为此使用PHP解决方案?
答案 0 :(得分:1)
您可以遍历所有行,修剪它们,然后在keyCode
为13
时测试长度,如下所示:
for(let i of lines){
if(e.keyCode == 13 && i.trim().length == 0) e.preventDefault()
}
您也可以使用some代替循环:
e.keyCode == 13 && lines.some(line => line.trim().length == 0) && e.preventDefault()
$('textarea').on('keydown', function(e) {
var text = $(".writeLines").val()
var lines = text.split(/\r\n|\n/)
// Disable enter on empty line
e.keyCode == 13 && lines.some(line => line.trim().length == 0) && e.preventDefault()
// Disable enter if there are 5 lines
e.keyCode == 13 && lines.length >= 5 && e.preventDefault()
})
// Disable pasting completely
.on('paste', e => e.preventDefault());
// When submitting:
$('form').on('submit', function(e) {
var lines = text.split(/\r\n|\n/)
(lines.some(line => line.trim().length == 0) || lines.length > 5) && e.preventDefault()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="writeLines" rows="8" cols="80"></textarea>
答案 1 :(得分:0)
这是另一种可能的解决方案:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<title>Ilan's Test</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div id="results">
<textarea class="writeLines" cols="25" rows="25"></textarea>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
// Set the initial counter
var count = 0;
// On press function
$('.writeLines').keypress(function(e) {
// Check the count, if it's less than 5 keep going
if (count >= 5) {
// Count is >= 5, for fun I disabled the textarea; you can do what you need here
console.log('we hit 5 lines');
$('.writeLines').attr('disabled', 'disabled');
return false
} else {
// Count is below 5, check is the enter key for a new line was pressed
if(e.which == 13) {
// If the key is a new line (a return), add to the count and console log it
count = count + 1;
console.log('the current line count is: ' + count);
} else {
// The key wasn't a new line, keep going and listen for the next key
return true;
}
}
});
});
</script>
</body>
</html>