Contact Form 7 and Cleave.js. Phone number input field

  cleave, contact-form-7, javascript, php

Thank you for paying attention to my question.

I am making a website for myself on WordPress, in parallel I am learning programming. I ask you to help sort out one point. I have implemented a contact form based on the Contact Form 7 plugin. I connected JS (cleave.js) to make it convenient to enter a phone number (only numbers and in a certain amount are entered). Everything works fine except for one thing: the field for entering the phone number stops working if the same contact form was already launched somewhere on the site. i.e. the same contact form is found on different pages of the site (for example: on the home page and on the internal page). On the home page, the field for entering the number works correctly, but on the internal page the conditions for the phone number field do not work.

Please tell me how to fix this so that the conditions for the number input field are triggered not only when opening the site, but on all pages where there is a contact form. The author advises using a loop by running instance.getRawValue (). Maybe there is another solution or JS that is easier to use.

Thanks!

JS link: https://github.com/nosir/cleave.js

Used code:

function enqueue_cleave(){
     wp_enqueue_script('cleave', get_stylesheet_directory_uri().'/js/cleave.min.js');
}
add_action('wp_enqueue_scripts', 'enqueue_cleave'); 

add_action('wp_footer', 'activate_cleave');

function activate_cleave(){
   if( is_page('') ){
?>

     <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', () => {
        var phone = new Cleave('#phone', {
            numericOnly:true,
            prefix:'+',
            delimiter:'-',
            blocks:[5,4,4,2]
        });
    });

     </script>

<?php 
   }
}

Source: Ask Javascript Questions

LEAVE A COMMENT