bootstrap-maxlength dos不适用于动态jquery对象

时间:2018-01-16 03:25:28

标签: javascript twitter-bootstrap-3 maxlength

我使用了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

1 个答案:

答案 0 :(得分:0)

尝试这种方式:

&#13;
&#13;
 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;
&#13;
&#13;