JavaScript를 사용하여 HTML에서 textArea에 maxlength를 적용하는 방법
내가 쓰면 어떤 기능을 갖고 싶습니다
<textarea maxlength="50"></textarea>
<textarea maxlength="150"></textarea>
<textarea maxlength="250"></textarea>
텍스트 영역에 최대 길이를 자동으로 부과합니다. 가능한 경우 jQuery에 솔루션을 제공하지 마십시오.
참고 : 다음과 같이하면이 작업을 수행 할 수 있습니다.
<textarea onkeypress="return imposeMaxLength(event, this, 110);" rows="4" cols="50">
function imposeMaxLength(Event, Object, MaxLen)
{
return (Object.value.length <= MaxLen)||(Event.keyCode == 8 ||Event.keyCode==46||(Event.keyCode>=35&&Event.keyCode<=40))
}
에서 복사 된 HTML 텍스트 영역에서 HTML 입력 "최대 길이"속성을 에뮬레이션하는 가장 좋은 방법은 무엇입니까?
그러나 요점은 textArea를 선언 할 때마다 onKeyPress 및 onKeyUp을 작성하고 싶지 않다는 것입니다.
window.onload = function() {
var txts = document.getElementsByTagName('TEXTAREA');
for(var i = 0, l = txts.length; i < l; i++) {
if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) {
var func = function() {
var len = parseInt(this.getAttribute("maxlength"), 10);
if(this.value.length > len) {
alert('Maximum length exceeded: ' + len);
this.value = this.value.substr(0, len);
return false;
}
}
txts[i].onkeyup = func;
txts[i].onblur = func;
}
};
}
jQuery를 피하고 싶지만 솔루션에 JavaScript가 필요 하므로이 솔루션 (jQuery 1.4 사용)이 가장 간결하고 강력합니다.
영감을 얻었지만 Dana Woodman의 답변에 비해 개선되었습니다.
그 대답의 변경 사항은 다음과 같습니다 .jQuery.live를 사용하여 간단하고 더 일반적이며 길이가 괜찮 으면 val을 설정하지 않습니다 (IE에서는 화살표 키를 사용하고 IE에서는 눈에 띄는 속도 향상).
// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').live('keyup blur', function() {
// Store the maxlength and value of the field.
var maxlength = $(this).attr('maxlength');
var val = $(this).val();
// Trim the field if it has content over the maxlength.
if (val.length > maxlength) {
$(this).val(val.slice(0, maxlength));
}
});
편집 : 대신 jQuery 1.7 이상 버전을 사용하여 업데이트on
live
// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').on('keyup blur', function() {
// Store the maxlength and value of the field.
var maxlength = $(this).attr('maxlength');
var val = $(this).val();
// Trim the field if it has content over the maxlength.
if (val.length > maxlength) {
$(this).val(val.slice(0, maxlength));
}
});
업데이트.live()
좀 더 강력하므로 대신 Eirik 솔루션을 사용하십시오 .
jQuery를 사용하지 않는 솔루션을 원했지만 Google을 통해이 페이지를 찾고 jQuery와 같은 솔루션을 찾는 사람을 위해 솔루션을 추가 할 것이라고 생각했습니다.
$(function() {
// Get all textareas that have a "maxlength" property.
$('textarea[maxlength]').each(function() {
// Store the jQuery object to be more efficient...
var $textarea = $(this);
// Store the maxlength and value of the field.
var maxlength = $textarea.attr('maxlength');
var val = $textarea.val();
// Trim the field if it has content over the maxlength.
$textarea.val(val.slice(0, maxlength));
// Bind the trimming behavior to the "keyup" event.
$textarea.bind('keyup', function() {
$textarea.val($textarea.val().slice(0, maxlength));
});
});
});
Google 직원에게 도움이 되길 바랍니다.
HTML5는 다음 과 같이 요소에 maxlength
속성을 추가합니다 textarea
.
<!DOCTYPE html>
<html>
<body>
<form action="processForm.php" action="post">
<label for="story">Tell me your story:</label><br>
<textarea id="story" maxlength="100"></textarea>
<input type="submit" value="Submit">
</form>
</body>
</html>
현재 Chrome 13, FF 5 및 Safari 5에서 지원됩니다. 당연히 IE 9에서는 지원되지 않습니다. (Win 7에서 테스트)
이 솔루션은 텍스트 중간에 문자가 추가 될 때 마지막 문자가 제거되는 IE의 문제를 방지합니다. 다른 브라우저에서도 잘 작동합니다.
$("textarea[maxlength]").keydown( function(e) {
var key = e.which; // backspace = 8, delete = 46, arrows = 37,38,39,40
if ( ( key >= 37 && key <= 40 ) || key == 8 || key == 46 ) return;
return $(this).val().length < $(this).attr( "maxlength" );
});
그런 다음 내 양식 유효성 검사는 사용자가 텍스트 영역의 최대 길이를 초과하는 텍스트를 붙여 넣을 수있는 문제 (IE에서만 문제가있는 것으로 보입니다)를 처리합니다.
이것은 내 사이트에서 방금 사용한 일부 조정 된 코드입니다. 남은 문자 수를 사용자에게 표시하는 것이 개선되었습니다.
(jQuery를 요청하지 않은 OP에게 다시 한 번 죄송하지만 요즘 누가 jQuery를 사용하지 않습니까?)
$(function() {
// Get all textareas that have a "maxlength" property.
$("textarea[maxlength]").each(function() {
// Store the jQuery object to be more efficient...
var $textarea = $(this);
// Store the maxlength and value of the field
var maxlength = $textarea.attr("maxlength");
// Add a DIV to display remaining characters to user
$textarea.after($("<div>").addClass("charsRemaining"));
// Bind the trimming behavior to the "keyup" & "blur" events (to handle mouse-based paste)
$textarea.on("keyup blur", function(event) {
// Fix OS-specific line-returns to do an accurate count
var val = $textarea.val().replace(/\r\n|\r|\n/g, "\r\n").slice(0, maxlength);
$textarea.val(val);
// Display updated count to user
$textarea.next(".charsRemaining").html(maxlength - val.length + " characters remaining");
}).trigger("blur");
});
});
국제 멀티 바이트 문자로 테스트되지 않았으므로 정확히 어떻게 작동하는지 잘 모르겠습니다.
또한 텍스트 영역에 붙여 넣기를 처리하려면 다음 이벤트를 추가하십시오.
...
txts[i].onkeyup = function() {
...
}
txts[i].paste = function() {
var len = parseInt(this.getAttribute("maxlength"), 10);
if (this.value.length + window.clipboardData.getData("Text").length > len) {
alert('Maximum length exceeded: ' + len);
this.value = this.value.substr(0, len);
return false;
}
}
...
maxlength 속성은 Internet Explorer 10, Firefox, Chrome 및 Safari에서 지원됩니다.
Note: The maxlength attribute of the
<textarea>
tag is not supported in Internet Explorer 9 and earlier versions, or in Opera.
from HTML maxlength Attribute w3schools.com
For IE8 or earlier versions you have to use the following
//only call this function in IE
function maxLengthLimit($textarea){
var maxlength = parseInt($textarea.attr("maxlength"));
//in IE7,maxlength attribute can't be got,I don't know why...
if($.browser.version=="7.0"){
maxlength = parseInt($textarea.attr("length"));
}
$textarea.bind("keyup blur",function(){
if(this.value.length>maxlength){
this.value=this.value.substr(0,maxlength);
}
});
}
P.S.
The maxlength attribute of the
<input>
tag is supported in all major browsers.
from HTML maxlength Attribute w3schools.com
Better Solution compared to trimming the value of the textarea.
$('textarea[maxlength]').live('keypress', function(e) {
var maxlength = $(this).attr('maxlength');
var val = $(this).val();
if (val.length > maxlength) {
return false;
}
});
You can use jQuery to make it easy and clear
JSFiddle DEMO
<textarea id="ta" max="10"></textarea>
<script>
$("#ta").keypress(function(e){
var k = e.which==0 ? e.keyCode : e.which;
//alert(k);
if(k==8 || k==37 || k==39 || k==46) return true;
var text = $(this).val();
var maxlength = $(this).attr("max");
if(text.length >= maxlength) {
return false;
}
return true;
});
</script>
It is tested in Firefox
, Google Chrome
and Opera
Small problem with code above is that val() does not trigger change() event, so if you using backbone.js (or another frameworks for model binding), model won't be updated.
I'm posting the solution worked great for me.
$(function () {
$(document).on('keyup', '.ie8 textarea[maxlength], .ie9 textarea[maxlength]', function (e) {
var maxLength = $(this).attr('maxlength');
if (e.keyCode > 47 && $(this).val().length >= maxLength) {
$(this).val($(this).val().substring(0, maxLength)).trigger('change');
}
return true;
});
});
I implemented maxlength
behaviour on textarea
recently, and run into problem described in this question: Chrome counts characters wrong in textarea with maxlength attribute.
So all implementations listed here will work little buggy. To solve this issue I add .replace(/(\r\n|\n|\r)/g, "11")
before .length
. And kept it in mind when cuting string.
I ended with something like this:
var maxlength = el.attr("maxlength");
var val = el.val();
var length = val.length;
var realLength = val.replace(/(\r\n|\n|\r)/g, "11").length;
if (realLength > maxlength) {
el.val(val.slice(0, maxlength - (realLength - length)));
}
Don't sure if it solves problem completely, but it works for me for now.
Try this jQuery which works in IE9, FF, Chrome and provides a countdown to users:
$("#comments").bind("keyup keydown", function() {
var max = 500;
var value = $(this).val();
var left = max - value.length;
if(left < 0) {
$(this).val( value.slice(0, left) );
left = 0;
}
$("#charcount").text(left);
});
<textarea id="comments" onkeyup="ismaxlength(this,500)"></textarea>
<span class="max-char-limit"><span id="charcount">500</span> characters left</span>
Try to use this code example:
$("#TextAreaID1").bind('input propertychange', function () {
var maxLength = 4000;
if ($(this).val().length > maxLength) {
$(this).val($(this).val().substring(0, maxLength));
}
});
This is much easier:
<textarea onKeyPress="return ( this.value.length < 1000 );"></textarea>
'programing tip' 카테고리의 다른 글
RHEL에 Python 3 설치 (0) | 2020.07.22 |
---|---|
앱에서 화면을 유지하려면 어떻게합니까? (0) | 2020.07.22 |
플래그 열거 형이 일반적으로 16 진 값으로 정의되는 이유 (0) | 2020.07.21 |
이름 노드가 안전 모드에 있습니다. (0) | 2020.07.21 |
android 조각 onRestoreInstanceState (0) | 2020.07.21 |