我使用了bootstrap-maxlength插件 https://github.com/mimo84/bootstrap-maxlength
var input ='<input type="text" id="text1" maxlength="20/>"';
var $input = $(input);
$input.maxlength(); //this dosn't work
$(p).parent().append($input); //p is the div element
答案 0 :(得分:0)
尝试这种方式:
jQuery(document).on('keyup','#myText',function() {
var maxlen=20;
var inputlen=$(this).val().length;
if(inputlen<=10)
{
$('#chars').addClass('badge badge-success');
}else if(inputlen<15 && inputlen>10){
$('#chars').addClass('badge badge-warning');
}else if(inputlen>15){
$('#chars').addClass('badge badge-danger');
}
$('#chars').text(inputlen +"/"+ maxlen);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css">
<div class="form-group">
<lable for="myText">Input Text<span id="chars" style="float:right"></span></lable>
<input type="text" class="form-control" id="myText" name="myText" maxlength="20"/>
</div>
&#13;