Home  >  Article  >  Web Front-end  >  TextArea does not support maxlength solution (jquery)_jquery

TextArea does not support maxlength solution (jquery)_jquery

WBOY
WBOYOriginal
2016-05-16 18:02:221186browse

I have been using .net controls for a long time. When adding length control to the TextBox of a page, I simply add maxlength='xxx', but the test always fails. The reason is that the multi-line mode is set. In this case In this case, the generated HTML code is textarea, and the maxlength attribute is not added because IE does not support the maxlength attribute of textarea. Therefore, after testing in firefox 6, it was found that firefox supports this attribute. Then it's simple. I wrote a jquery extension myself, so that I can easily control the maximum length of textarea.
The extension code is as follows:

Copy code The code is as follows:

(function($) {
$.fn.textarealimit = function(settings) {
settings = jQuery.extend({
length:1000
}, settings);
maxLength =settings.length;
$(this).attr("maxlength",maxLength).bind("keydown",doKeydown).bind("keypress",doKeypress).bind("beforepaste",doBeforePaste).bind("paste",doPaste) ;
function doKeypress()
{
var oTR = document.selection.createRange()
if(oTR.text.length >= 1)
event.returnValue = true
else if(this.value.length > maxLength-1)
event.returnValue = false
}
function doKeydown()
{
var _obj=this;
setTimeout (function()
{
if(_obj.value.length > maxLength-1)
{
var oTR = window.document.selection.createRange()
oTR.moveStart( "character", -1*(_obj.value.length-maxLength))
oTR.text = ""
}
},1)
}
function doBeforePaste()
{
event.returnValue = false
}
function doPaste()
{
event.returnValue = false
var oTR = document.selection.createRange()
var iInsertLength = maxLength - this.value.length oTR.text.length
var sData = window.clipboardData.getData("Text").substr(0, iInsertLength)
oTR.text = sData;
}
}
})(jQuery);

The above only controls the copy and paste control and input control for IE. Due to the characteristics of IE, these methods are invalid in firefox. of.
Call code:
Copy code The code is as follows:

$(document).ready (function() {
$("#ctl00_ZiiOContent_ucQuestionnaire_txtquestion4_2").textarealimit();
});
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn