A
A
Anton2015-11-02 06:11:00
JavaScript
Anton, 2015-11-02 06:11:00

Checking the number of characters entered in the field, there is an error, throws it to the end of the text, how to fix it?

Hello, for some fields on the site, I set a limit on the input of characters, and added a script that shows how many letters were entered, so at first I didn’t notice that if I edit the text and edit a letter or add somewhere in the middle of the text, then it throws it to the end text, if you put a slash and try to write.

I realized that this is a problem in js, which counts how many letters were entered, everything is ok in mozilla, in chrome it throws it to the end, help fix js, tell me what the problem is.

<script>

    $(function () {
        var maxLength = $('#textarea').attr('maxlength');
        $('#textarea').keyup(function () {
            var curLength = $('#textarea').val().length;
            $(this).val($(this).val().substr(0, maxLength));
            var remaning = maxLength - curLength;
            if (remaning < 0) remaning = 0;
            $('#textareaFeedback').html(' - осталось ( ' + remaning + ' ) символов ');
            if (remaning < 15) // когда менять цвет
            {
                $('#textareaFeedback').addClass('warning')
            }
            else {
                $('#textareaFeedback').removeClass('warning')
            }
        })
    })
</script>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly Inchin ☢, 2015-11-02
@In4in

1) Use input instead of keyup . 2) You change the value of a field when it has focus. It is quite natural that the input position flies. The way out is quite simple - you need to use the selectionStart/End properties (or setSelectionRange ).

var $area = $("#textarea"), $feed = $("#textareaFeedback");

$('#textarea').on("input", function(){
   var val = this.value, selStart = this.selectionStart;

   val.length > maxLength && $area
       .val( val.substr(0, maxLength) )
       .prop({
          selectionStart : selStart,
          selectionEnd : selStart
       })
   ;
   
    var remaning = Math.max(maxLength - val.length, 0);
    $feed.html(' - осталось ( ' + remaning + ' ) символов ')
        .toggleClass('warning', remaning < 15);
});

jsfiddle.net/In4in/nyg7dy3o
I take it you don't like maxlength support ?

R
Rsa97, 2015-11-02
@Rsa97

$(this).val($(this).val().substr(0, maxLength));
Remove this line. You completely rewrite the value of the field, different browsers may behave differently in this case. In addition, the maxlength attribute is already set, and such an additional restriction does not make sense.
By the way, in addition to keyup, you also need to process paste and cut.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question