简体   繁体   中英

Run function on ready and on click but not on already existing elements

I'm just a sysadmin so not so good with JS. I have wrote this code

// initializing libraries flatpikr, inputmask and sortable
function initializeFormLib(){
    //for datepicker only where is not already initialized
    jQuery('[name="data-partenza"]:not(.flatpickr-input)').flatpickr({
        locale:'it', 
        minDate: "today",
        dateFormat: "Y-m-d",
        ariaDateFormat: "Y-m-d",    
        disableMobile: true,
        altInput: true,
        altFormat: "j F Y", 
    });
    //for input masks
    jQuery('[name="destinazione"],[name="sistemazione"]').inputmask({
        regex:"([A-zÀ-ú\ ]+)",
        "placeholder": "",
        "onincomplete": function(){ jQuery(this).attr('value','').val('')}
    });
    jQuery('[name="tipologia"]').inputmask({
        regex:"([A-zÀ-ú\ ]+)",
        "placeholder": "",          
        "onincomplete": function(){ jQuery(this).attr('value','').val('')}
    });             
    jQuery('[name="prezzo"]').inputmask({
        mask:"99[9].99",
        "onincomplete": function(){ jQuery(this).attr('value','').val('')}
    });
    //for sortable
    jQuery(".sortable").sortable({  item: ".duplicable", });
};
jQuery(document).on('ready', function () {
    initializeFormLib();
});

As you can see this is providing some libraries to a form like calendars input mask etc, this is working as expected. Problem is that the form is dynamically increasing the number of fields by clicking on a plus icon that has class 'dashicons-plus-alt'. This happens through this code that is working and at the end is running again the initializeFormLib(), so the newly added fields will have calendars etc too

//duplication
jQuery(document).on("click", ".dashicons-plus-alt", function() {
    <?php ob_start(); ?>
    var formDatiEvento = <?php echo json_encode(formDatiEvento(['destinazione'][''])) ?>;
    <?php echo ob_get_clean(); ?>   
    var formDatiEventoObj = jQuery(formDatiEvento)[0].outerHTML;
    var duplicable = jQuery(this).closest('.duplicable');
    var duplicableClasses = duplicable[0].classList[0];
    duplicable.after(jQuery(formDatiEventoObj).find('.' + duplicableClasses)[0].outerHTML);
    //svuoto i campi e animo la duplicazione
    jQuery('.duplicable').fadeIn('slow');
    //clicco sul bottone per il collapse delle date in maniera da riadattare l'altezza del container
    if ( jQuery(this).closest('.container-data').height() > 40 ) {
        jQuery(this).closest('.container-data').find('.dashicons-arrow-down-alt2').click();
    }
    //reinitializing libraries flatpikr, inputmask and sortable
    initializeFormLib();
});

the problem here is that when I'm clicking on the plus button, the code is running the function initializeFormLib() again on existing fields, and this is breaking things like destroying already filled calendars or breaking the input masks. I fixed the calendar side applying a condition to the flatpicker selector :not(.flatpickr-input), in this way I can avoid to run the flatpicker on already present fields, but the input mask library doesn't add any particular class to the initialized fields, furthermore I think that this is not the correct way, just a bad fix.

I fixed in this way

//un po di funzioni da eseguire quando inizializzo il form (es. calendario, riposizionamenti,maschere ecc)
function initializeFormLib(){
    //per datepicker solo dove non è stato inizializzato
    jQuery('[name="data-partenza"]:not(.flatpickr-input)').flatpickr({
        locale:'it', 
        minDate: "today",
        dateFormat: "Y-m-d",
        ariaDateFormat: "Y-m-d",    
        disableMobile: true,
        altInput: true,
        altFormat: "j F Y", 
    });
    //per campi mascherati
    jQuery
    jQuery('[name="destinazione"]:not(".masked"),[name="sistemazione"]:not(".masked"),[name="tipologia"]:not(".masked")').addClass('masked').inputmask({
        regex:"([A-zÀ-ú\ ]+)",
        "placeholder": "",
        "onincomplete": function(){ jQuery(this).attr('value','').val('')}
    });
    jQuery('[name="prezzo"]:not(".masked")').addClass('masked').inputmask({
        mask:"99[9].99",
        "onincomplete": function(){ jQuery(this).attr('value','').val('')}
    });
    //per riposizionamento dei campi
    jQuery('.sortable:not(".ui-sortable")').sortable({item: '.duplicable'});
};
jQuery(function() {
    initializeFormLib();
});

basically I'm adding .addClass('masked') and a not selector based on this class, in this way the functions are not applied again on already existing fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM