jQuery文本区域计数器

jQuery textarea counter

本文关键字:计数器 区域 文本 jQuery      更新时间:2023-09-26

我有这个jQuery代码

$(window).load(function () {
    $('document').ready(function () {
        var text_max = "5000";
        $('#ram').html(text_max + '/5000');
        window.setInterval(function () {
            $("#post").attr("maxlength", "5000");
            var text_length = $('#post').val().length;
            var text_remaining = text_max - text_length;
            if ($("#post").val().length < 4750) {
                $('#ram').html('<abbr title="You Have ' + text_remaining + ' Characters Remaining In This Post" style="visibility: hidden;">' + text_remaining + '/5000</abbr>');
            } else {
                $('#ram').html('<abbr title="You Have ' + text_remaining + ' Characters Remaining In This Post">' + text_remaining + '/5000</abbr>');
            }
            if ($("#post").val().length <= 5000) {
                $("#subm").removeAttr("disabled");
            } else {
                $("#subm").attr("disabled", "disabled");
            }
            if ($("#post").val().length < 4980) {
                $("#ram").removeAttr("style");
            } else {
                $("#ram").attr("style", "color:#ff0000;");
            }
        });
    });
});

和我的HTML:

<form action='posting' method='POST'><center><font color='#ff0000' style='style=font-family: Sarala, sans-serif;display: inline-block;word-break: break-word;'></font><br><table><tr><td><textarea rows='15' cols='40' style='resize: none;max-width: 297px;max-height: 225px;width: 297px;height: 225px;' name='post' id='post' maxlength='5000' spellcheck='true' autofocus></textarea></center></td></tr><tr><td><div class='ram' id='ram' name='ram'><noscript><center>There Is A 500 Character Limit On All Posts</center></noscript></div></td></tr></table></td></tr><tr><td><center><input type='submit' value='Post&#33;' class='subm' id='subm' name='subm'></center></td></tr></table></form>

然而,我希望它计算文本区域的适当值,但这是因为当您按enter时,它将其计算为2而不是1。我需要做的是将值取为相等的值,而不是不相等的值。有没有任何方法可以做到这一点,使用下面的代码。或者我是否完全需要重做,如果是的话,我不擅长jQueryJavascript;所以我需要你的帮助??

谢谢!!!

好的,这里有一些东西。

首先;您可以使用keyUp事件(尽管最好使用.on('keyup', handler)变体)。因为到目前为止,你只是在无休止地循环,而你不想每次都检查用户是否没有做任何事情,对吧?

此外;jQuery(document).ready();回调就足够了,不需要将其封装在jQuery(window).load()回调中。

然后,我将根据需要添加/删除类。它使它更易于维护。根据经验,您不希望在脚本中添加样式。这就是css的作用。

我觉得这个小剧本符合你的要求。请在此处查看演示

jQuery(document).ready(function ($) {
    // Calculate remaining characters
    function charactersRemaining() {
        var charactersAllowed = $('input[name="characters-allowed"]').val();
        return {
            allowed: charactersAllowed,
            remaining: charactersAllowed - $('textarea[name="post"]').val().length
        };
    };
    // Do stuff when calculated the characters
    function updateCharacterCount() {
    var characterCount = charactersRemaining();
    // Update notifiers
    $('.characters-remaining').text(characterCount.remaining);
    $('.allowed-characters').text(characterCount.allowed);
    // Update properties and classes
    if( characterCount.remaining < 0 ) {
        $('button.submit').prop('disabled', true);
    } else {
        $('button.submit').prop('disabled', false);
    }
    if( characterCount.remaining <= 0 ) {
        $('.character-count').addClass('overflow');
      $('textarea[name="post"]').addClass('limit');
    } else {
        $('.character-count').removeClass('overflow');
      $('textarea[name="post"]').removeClass('limit');
    }
  };
  // Register events for form fields
  $('textarea[name="post"], input[name="characters-allowed"]').on('keyup', function() {
    updateCharacterCount();
  });
  // As a little extra disallow typing of extra characters
  $('body').on('keydown', 'textarea[name="post"].limit', function(e) {
    var keyCode = e.keyCode || e.which;
    if( keyCode !== 8 && keyCode !== 46 ) { // allow backspace and delete button
        e.preventDefault();
    }
  });
  // initialize
  updateCharacterCount();
});

请注意;到目前为止,键入受到限制,每当字符溢出时,post按钮就会被禁用。这听起来很愚蠢,但你仍然可以粘贴超过允许的字符。你可以构建一个去掉多余字符的函数。但我太懒了。如果你愿意,你也可以把它转换成一个插件。但我也太懒了;)

我很好奇,因为在我的电脑上我不能重复你的问题。你能测试一下我的片段吗?

$(function () {
  var text_max = 5000;
  $("#post").attr("maxlength", text_max);
  $('#ram').html('<abbr title="You Have ' + text_max + ' Characters Remaining In This Post">' + text_max + '/5000</abbr>');
  $('#post').on('keyup', function () {
    var text_length = $('#post').val().length;
    var text_remaining = text_max - text_length;
    $('#ram').html('<abbr title="You Have ' + text_remaining + ' Characters Remaining In This Post">' + text_remaining + '/5000</abbr>');
    if ($("#post").val().length < 5000) {
      $("#subm").removeAttr("disabled");
    } else {
      $("#subm").attr("disabled", "disabled");
    }
    if ($("#post").val().length < 4980) {
      $("#ram").removeAttr("style");
    } else {
      $("#ram").attr("style", "color:#ff0000;");
    }
  });
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<form action='posting' method='POST'>
    <center><font color='#ff0000'
                  style='style=font-family: Sarala, sans-serif;display: inline-block;word-break: break-word;'></font><br>
        <table>
            <tr>
                <td><textarea rows='15' cols='40'
                              style='resize: none;max-width: 297px;max-height: 225px;width: 297px;height: 225px;'
                              name='post' id='post' maxlength='5000' spellcheck='true' autofocus></textarea>
    </center>
    </td></tr>
    <tr>
        <td>
            <div class='ram' id='ram' name='ram'>
                <noscript>
                    <center>There Is A 500 Character Limit On All Posts</center>
                </noscript>
            </div>
        </td>
    </tr>
    </table></td></tr>
    <tr>
        <td>
            <center><input type='submit' value='Post&#33;' class='subm' id='subm' name='subm'></center>
        </td>
    </tr>
    </table>
</form>