I am trying to append -
between phone numbers in user input to be like xxx-xxx-xxxx
instead of xxxxxxxxxx
.
This is working fine when using Keys to enter value but what about Pasting the number or Chrome Auto-fill function? For example if you copy and paste 2222222222
to the input the -
will not added between.
How can I fix this?
$(function () {
$('#txtnumber').keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$text = $(this);
if (key !== 8 && key !== 9) {
if ($text.val().length === 3) {
$text.val($text.val() + '-');
}
if ($text.val().length === 7) {
$text.val($text.val() + '-');
}
}
return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="txtnumber" type="text" maxlength="12" placeholder="xxx-xxx-xxxx" /><br /><br />