js監聽input輸入字符變化


  <p class="text-input">
        <input type="text" id="username" autoComplete='off' maxlength="30">
        <span class="js_limit">
            <em>0</em>/<span>30</span>
        </span>
    </p>

    <script src="jquery-1.7.2.min.js"></script>
    <script>
        $(function(){
            $('#username').bind('input propertychange', function() {
                $('.js_limit em').html($(this).val().length);
            });
        })
    </script>

 要是想監聽輸入字符的數量變化,同時超出的字符部分自動截取:

  <p class="text-input">
        <input type="text" id="username" autoComplete='off' maxlength="15" onkeyUp="textLimitCheck(this, 15);">
        <span class="js_limit">
            <em id="messageCount">0</em>/<span>15</span>
        </span>
    </p>
    <script>
        function textLimitCheck(thisArea, maxLength){ if (thisArea.value.length > maxLength){ alert(maxLength + ' 個字限制. \r超出的將自動去除.'); thisArea.value = thisArea.value.substring(0, 15); thisArea.focus(); } /*回寫span的值,當前填寫文字的數量*/ messageCount.innerText = thisArea.value.length; } </script>

試過了這個方法才知道,原來只用監聽字符數量就行,屬性maxlength就可以完成自動截取字符的功能


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM