2011-09-21 4 views
1

작은 문자 카운터 & 리미터를 썼습니다.
당신은 여기를 테스트 할 수 Char Counter & Limiter문자 카운터 & 리미터 - 코드 투명도

jQuery를 코드 :

$(document).ready(function() { 

$('.counter').each(function(index) { 

    $('.counter p span').html('0'); // set character length to 0 
    $('input', this).keyup(function() { 

     var CounterDiv = $(this).parent(); // 
     var Limit = $('p', CounterDiv).html().split('/')[1]; 
     var CurrentLength = $(this).val().length; 

     if (CurrentLength == Limit) { 

      $('p span', CounterDiv).html(CurrentLength); 
      return false; 

     } else if (CurrentLength > Limit) { 

      var str = $(this).val(); 
      $(this).val(str.substring(0, str.length - 1)); 
      return false; 

     } else { 

      $('p span', CounterDiv).html(CurrentLength); 

     } 
    }); 

}); 

}); 

당신은 어떻게 그것을 향상시킬 수있는 제안을 가지고 있나요? 구문에 100 % 확실하지 않습니다. 입력 여기

에 대한

답변

3

를 사용하여 기본 HTML maxlength 속성은 샘플입니다 : http://jsfiddle.net/8YdCh/16/

HTML

<input name="input1" type="text" maxlength="8" /> 

JS

$(document).ready(function() { 
    $('.counter').each(function(index) { 
     $('.counter p span').html('0'); // set character length to 0 
     $('input', this).keyup(function() { 
      var $countSpan = $(this).parent().find('.var-count'); // find the count span 
      var countValue = $(this).val().length + "/" + $(this).attr('maxlength'); // format value for count span 'current value lenght/maxlength attribute' 
      $countSpan.text(countValue); // set formatted value to your column span 
     }); 
    }); 
}); 
+0

잠시 창을 띄워서 설명해 주시겠습니까? 텍스트 ($ (this)) .val(). 길이 + "/"+ $ (this) .attr ('maxlength')); ' – Iladarsda

+1

당신의 스팬에 당신의 심볼을 표시하는 것뿐입니다. 잠시만 기다려주세요. 덧글을 추가하겠습니다. – Samich

+0

이 경우에는 텍스트 상자의 값을 제한하는 논리가 없습니다. 그것은 브라우저 자체로 수행됩니다. – Samich