Zachary
Zachary

Reputation: 300

Length - 1 takes off more then it should in JS

I am having an odd problem with my code. Every time the user goes to hit backspace it removes three numbers off the end. I am currently using $(this).val($(this).val().substring(0, $(this).val().length - 1)); to take one number off the end but its removing more then it should. Did I do something wrong?

on('keydown keyup', '.type-date', function(e) {
        $(this).attr('maxlength', '10');
        var value = $(this).val();
        var key = String.fromCharCode(e.keyCode);
        if (!(key >= 0 && key <= 9))
            $(this).val($(this).val().substring(0, $(this).val().length - 1));
        if (value.length == 2 || value.length == 5)
            $(this).val($(this).val() + '/');
        $('.type-date').attr('value', value);
    });

Upvotes: 0

Views: 36

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36574

The function is executed two time on keydown and then keyup. Just trigger function on keyup

$('.type-date').on('keyup', function(e) {
        $(this).attr('maxlength', '10');
        var value = $(this).val();
        var key = String.fromCharCode(e.keyCode);
        if (!(key >= 0 && key <= 9))
            $(this).val($(this).val().substring(0, $(this).val().length));
        if (value.length == 2 || value.length == 5)
            $(this).val($(this).val() + '/');
        $('.type-date').attr('value', value);
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="type-date" />

Upvotes: 1

Related Questions