I’ve been trying to implement a code snippet for the telephone input field in my WordPress FunnelKit builder checkout, but it isn’t working as expected when users re-enter their numbers. I aim to create an input format similar to the one on this example, with a few modifications. Specifically, I would like to fix the initial 0 digit at the start of the field, so as the user types, the format appears as:
(056) 234-56-67
The 0 digit should remain fixed at the start as they continue typing. Below is the previous code snippet I added to functions.php, but it doesn’t fully achieve the intended behavior. Could you please assist with a solution that aligns with this format?
Thank you!
add_action( 'wp_footer', 'funnelkit_phone_mask' );
function funnelkit_phone_mask() {
wc_enqueue_js( "
$('#tel_no, #alt_tel_no')
.keydown(function(e) {
var key = e.which || e.charCode || e.keyCode || 0;
var phone = $(this);
// Don't allow anything but numbers and some control keys
if (key !== 8 && key !== 9) {
if (phone.val().length === 0) {
phone.val('(' + phone.val()); // add opening bracket
}
if (phone.val().length === 4) {
phone.val(phone.val() + ') '); // add closing bracket and space after area code
}
if (phone.val().length === 9) {
phone.val(phone.val() + '-'); // add first hyphen after 3 digits
}
if (phone.val().length === 12) {
phone.val(phone.val() + '-'); // add second hyphen after 2 more digits
}
}
return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});
" );
}
// Function to set the placeholder and maxlength for both phone fields
add_action( 'wp_footer', 'funnelkit_phone_placeholder' );
function funnelkit_phone_placeholder() {
wc_enqueue_js( "
// Set placeholder and maxlength for tel_no field
$('#tel_no').attr('placeholder', 'Tel. nömrəsi (___) ___-__-__');
$('#tel_no').attr('maxlength', '15'); // Limit input to 15 characters
// Set placeholder for alt_tel_no field
$('#alt_tel_no').attr('placeholder', 'Alternativ tel. nomresi (___) ___-__-__');
$('#alt_tel_no').attr('maxlength', '15'); // Limit input to 15 characters
" );
}