1

I have this jQuery code

$(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;");
            }
        });
    });
});

And My 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>

However I want it to account the appropriate value of the textarea, however this is because when you press enter it accounts it as 2 instead of 1. What I need to do is to get the value to an equal amount opposed to an unequal amount. Is there any way of doing this, with the code below. Or would I completely need to redo it, if so I am not good at jQuery or Javascript; so I will need your help??

Thanks!!!

antipanchi
  • 29
  • 1
  • 10

2 Answers2

1

Ok, there are a few things here.

First of all; you can use the keyUp event (although it's beter to use the .on('keyup', handler) variant). Because as of now you're just looping endlessly, while you don't want to check everytime if the user didn't do anything, right?

Furthermore; the jQuery(document).ready(); callback is more then enough, you don't need to wrap it in the jQuery(window).load() callback.

Then I would just add/remove classes as appropriate. It makes it a lot easier to maintain. As a rule of the thumb, you don't want to add styling in your scripts. That's what css is for.

I think this little script does what you want. Checkout the demo here.

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();

});

Please note; as of now typing is limited, and the post button is disabled whenever characters do overflow. This sounds stupid, but you can still paste more then allowed characters. You could build in a function that strips off extra characters. But I was too lazy for that. You can also transform this into a plugin if you'd like. But I was also too lazy for that ;)

giorgio
  • 10,111
  • 2
  • 28
  • 41
  • Could you please explain about how it works as I might want to make a few changes – antipanchi Mar 26 '16 at 16:29
  • This also breaks on high order unicode and multi-byte characters where a character doesn't fit into USC2/UTF16. – Jeremy J Starcher Mar 26 '16 at 16:30
  • Not sure but using onchange might solve the paste issue. – Rajesh Mar 27 '16 at 03:21
  • @antipanchi it's all quite straightforward, checkout the jQuery api docs for explanation of used functions like `prop()` and `on()`. But basically I did three things; first I built a function to calculate how many characters are left. Second I built a function to change the DOM whenever needed (add/remove css classes and text in the notifiers to visually tell the user what's going on). And third I attached events to the textarea and the allowed characters input field which fires the function that changes the DOM if needed. And a little bonus to prevent the user to write extra characters. – giorgio Mar 27 '16 at 14:02
0

I'm curious because on my computer I cannot repeat your problem. Could you test my snippet?

$(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>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61