JSFiddle - React, Tailwind, and code Playground

by Brajinder Singh

HTML

<input type="text" class="creditCardText" maxlength="19" />

JavaScript

$('.creditCardText').keyup(function () {
    var cctlength = $(this).val().length; // get character length

    switch (cctlength) {
        case 4:
            var cctVal = $(this).val();
            var cctNewVal = cctVal + '-';
            $(this).val(cctNewVal);
            break;
        case 9:
            var cctVal = $(this).val();
            var cctNewVal = cctVal + '-';
            $(this).val(cctNewVal);
            break;
        case 14:
            var cctVal = $(this).val();
            var cctNewVal = cctVal + '-';
            $(this).val(cctNewVal);
            break;
        default:
            break;
    }
});