let $btnIndietro; let $btnAvanti; let $btnSubmit; let $collapses; let $form; let $modal; const endpoint = '/nqcontent/include/zoo25/form/2027/visitors/ajax/feed.cfm'; // RegEx per Codice Fiscale (CF): 16 caratteri A-Z e 0-9 con struttura fissa. const cfRegex = /^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/; // RegEx per sitoweb url completo di https (sostituito con la funzione isValidHttpUrl) const websiteREGex = /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm; // RegEx per Partita IVA (PIVA) Generica: Alfanumerico senza spazi/simboli. const pivaGenericRegex = /^[A-Z0-9]+$/; // RegEx per email const regex_email_valida = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\\.,;:\s@\"]+\.)+[^<>()[\]\\.,;:\s@\"]{2,})$/i; // RegEx per password che deve contenere >8 e <20 caratteri, almeno una lettera maiuscola, un numero e un simbolo (es. ! @ # $). //const regex_password_valida = /^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>])[A-Za-z\d!@#$%^&*(),.?":{}|<>]{8,20}$/; const regex_password_valida = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_])[^\s]{8,20}$/; $(function(){ if(editProfile){ var status = $('#status').val(); if(status == 'WEB_ACTIVE'){ // viene generato e iniettato un link(generato in _form.cfm userData) per il cambio password var container_password_link = $('
').addClass('col-md-12 text-center col-12 mb-3'); var link = $('').attr('href', userData[0].link_change_password).attr('target', '_blank').addClass('btn btn-speciale-bianco').text(jsLabelDictionary.label_set_new_pwd); container_password_link.append(link); $('#email').parent().parent().parent().append(container_password_link); } // aggiungo il bottone di invio della form var btn_submit = $('').attr('type', 'button').addClass('btn btn-speciale-fucsia btn-submit').text(jsLabelDictionary.label_salva); $('.btn-position-right').last().append(btn_submit); } // istanzio le multipicklist $('.form-select-multi').select2({ theme: "bootstrap-5", width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style', placeholder: jsLabelDictionary.label_search_select, allowClear: true, closeOnSelect: false }); /* GESTIONE MOVIMENTI ACCORDION */ $btnIndietro = $('.btn-prev'); $btnAvanti = $('.btn-next'); $btnSubmit = $('.btn-submit'); $collapses = $('#accordion-form-visitors .accordion-collapse'); $form = $('#visitors-form'); $modal = $('#modal_visitor_register'); $btnIndietro.on('click', function(e){ e.preventDefault(); var p = $(this).data('prev-step-id'); var n = $(this).data('next-step-id'); var t = $(this).data('this-step-id'); //console.log('click prev btn', p,n,t); stepBack(p,n,t); }); $btnAvanti.on('click', function(e){ e.preventDefault(); var p = $(this).data('prev-step-id'); var n = $(this).data('next-step-id'); var t = $(this).data('this-step-id'); //console.log('click next btn', p,n,t); stepForward(p,n,t); }); $btnSubmit.on('click', async function(e) { e.preventDefault(); const risultato = await validateSection(6); if (risultato) { //chiudi last accordion clickOnButtonAccordion(6); // disabilita last accordion button $('#visitors_head_button_6').prop('disabled', true); // invia form $form.submit(); } }); /* end GESTIONE MOVIMENTI ACCORDION */ // blocco tasto invio $form.on('keypress', function(event){ if (event.which == '13') { event.preventDefault(); } }); $('#motivo_reg').on('change', function(e){ e.preventDefault(); let me = $(this); // EXTRA RULEZ --------------------------- // Qualora l'utente selezioni opzione 1 o 2 deve comparire il testo: // "Se vuoi esporre o se stai cercando distributori, compila il form dedicato. CLICCA QUI" // --------------------------------------- if(me.val() == '1' || me.val() == '2'){ var textModal = jsLabelDictionary.label_compila_form_dedicato_1.replace('[link_click]', linkFormEspositore); $('#modalError').find('.modal-body').html(textModal); if(editProfile){ // nasconde btn chiudi $('#modalError_close_btn').addClass('d-none'); // appende un bottone nuovo con link var btn_link = $('').addClass('btn btn-speciale-fucsia').attr('href', jsLabelDictionary.diventa_esitore_page).html(jsLabelDictionary.vrm_scarica_free_btn_2); $('#modalError').find('.modal-footer').empty().append(btn_link); $('#modalError').modal('show'); } else{ $('#modal_visitor_register').modal('hide'); $('#modal_visitor_register').on('hidden.bs.modal', function(e){ // nasconde btn chiudi $('#modalError_close_btn').addClass('d-none'); // appende un bottone nuovo con link var btn_link = $('').addClass('btn btn-speciale-fucsia').attr('href', jsLabelDictionary.diventa_esitore_page).html(jsLabelDictionary.vrm_scarica_free_btn_2); $('#modalError').find('.modal-footer').empty().append(btn_link); $('#modalError').modal('show'); }); } } }); $('#vat').parent().find('.form-text').addClass('d-none'); $('#country').on('change', function(e){ e.preventDefault(); let me = $(this); const selectedOption = me.find('option:selected'); const prefixValue = selectedOption.data('prefix'); const ZoneValue = selectedOption.attr('data-zone'); const ZoneBlackList = selectedOption.attr('data-blacklist'); // console.log(prefixValue, ZoneValue, ZoneBlackList) //if(ZoneBlackList == 'false'){ $('.btn-next').prop('disabled', false); loadState('&country=' + me.val()); var ELs = $('#state'); ELs.empty(); var options2 = $('').val('').html(jsLabelDictionary.label_choose); ELs.append(options2).prop('required', false).removeClass('is-valid valid').parent().addClass('visually-hidden-focusable'); $('#vat, #cod_fiscale').removeClass('is-invalid'); $('#vat').prop('required', true); //if(ZoneValue == 'CEE'){ if(me.val() == 'ITALIA'){ //$('#vat').prop('required', false); $('#vat').parent().find('.form-text').removeClass('d-none'); $('#cod_fiscale').parent().removeClass('d-none'); } else{ //$('#vat').prop('required', true); $('#vat').parent().find('.form-text').addClass('d-none'); $('#cod_fiscale').prop('required', false).val('').parent().addClass('d-none'); } setMandatoryLabel(); $('#phone_prefix').val(prefixValue); //} //else{ // ZONE IN BLACK LIST //$('.btn-next').prop('disabled', true); //$('#modalError').find('.modal-body').html(jsLabelDictionary.label_modal_body_country_blacklist); //$('#modalError').modal('show'); //} }); $('#tipology').on('change', function(e){ e.preventDefault(); let me = $(this); let activity = $('#activity'); let tipology_other = $('#tipology_other') let user_role = $('#user_role'); let job_title = $('#job_title'); loadAttivita(me.val()); loadDimAzienda(me.val()); loadNSalesPoints(me.val()); loadRuoloContatto(me.val()); // reset delle picklist sotto job_title.empty(); activity.val(''); // vedi/nascondi campi del blocco 'la tua attivit' switch (me.val()) { case '13' : // stampa $('#market_placement').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#market_placement_other').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#main_distribution_channel').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#main_distribution_channel_other').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#testata_giornalistica').prop('required', true).parent().removeClass('visually-hidden-focusable'); $('#target_giornalista').prop('required', true).parent().removeClass('visually-hidden-focusable'); loadAreaGeograficaTrattata(); break; case '14': // blogger $('#main_distribution_channel').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#main_distribution_channel_other').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#market_placement').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#market_placement_other').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); loadAreaGeograficaTrattata(); break; case '16': // associazioni $('#main_distribution_channel').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#main_distribution_channel_other').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#market_placement').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#market_placement_other').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); loadAreaGeograficaTrattata(); break; case '99': // altro $('#market_placement').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#market_placement_other').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#main_distribution_channel').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#main_distribution_channel_other').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#covered_markets').parent().addClass('visually-hidden-focusable'); $('#testata_giornalistica').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#target_giornalista').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); tipology_other.parent().removeClass('visually-hidden-focusable'); tipology_other.prop('required', true).trigger('focus'); setTimeout(() => { activity.val('099'); activity.trigger('change'); }, 1000); break; default : $('#market_placement').prop('required', true).val('').parent().removeClass('visually-hidden-focusable'); $('#market_placement_other').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#main_distribution_channel').prop('required', true).val('').parent().removeClass('visually-hidden-focusable'); $('#main_distribution_channel_other').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#covered_markets').parent().removeClass('visually-hidden-focusable'); loadMarketPlacement(); loadMainDistributionChannel() loadAreaGeograficaTrattata(); tipology_other.parent().addClass('visually-hidden-focusable'); tipology_other.prop('required', false); $('#testata_giornalistica').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); $('#target_giornalista').prop('required', false).val('').parent().addClass('visually-hidden-focusable'); break; } setMandatoryLabel(); }); $('#activity').on('change', function(e){ e.preventDefault(); let me = $(this); let typology = $('#tipology'); let n_sales_point = $('#n_sales_point'); let user_role = $('#user_role'); let job_title = $('#job_title'); // EXTRA RULEZ --------------------------- // per la tipologia RIVENDITORI e attivit "E-commerce" il campo "punti vendita" si setta in automatico su "solo "e-commerce" cod 6 // per la tipologia RIVENDITORI e attivit "Negozio singolo pet" il campo "punti vendita" si setta in automatico a 1 // Per l'attivit "Blogger/Vlogger", l'utente sceglie il ruolo ma la job si sett in automatico cn Job=16 // Per l'attivit "content creator", l'utente sceglie il ruolo ma la job si sett in automatico Job=29 // Per l'attivit "dog trainer", ruolo e job si impostano in automatico: : ruolo = LP e Job=49 // Per l'attivit "fotografo", ruolo e job si impostano in automatico: ruolo = LP e Job=54 // Per l'attivit "nutrizionista", l'utente sceglie il ruolo ma la job si setta in automatico con Job=64 // Per l'attivit "pet sitter", ruolo e job si settano in automatico: ruolo = LP e Job=69 // ---------------------------------------- // type RIVENDITORI if(typology.val() == '10'){ if(me.val() == '035'){ // E-commerce n_sales_point.val('6'); //Solo E-commerce n_sales_point.parent().addClass('visually-hidden-focusable'); n_sales_point.trigger('change'); } else{ n_sales_point.parent().removeClass('visually-hidden-focusable'); } if(me.val() == '042'){ // Negozio singolo pet n_sales_point.val('1'); // 1 n_sales_point.parent().addClass('visually-hidden-focusable'); n_sales_point.trigger('change'); } else{ n_sales_point.parent().removeClass('visually-hidden-focusable'); } } switch (me.val()) { case '056' : // Blogger/Vlogger user_role.val('LP').trigger('change'); job_title.attr('data-selected', '16'); job_title.trigger('change'); break; case '057' : // content creator user_role.val('LP').trigger('change'); job_title.attr('data-selected', '29'); job_title.trigger('change'); break; case '066' : // dog trainer user_role.attr('data-selected', 'LP'); user_role.trigger('change'); job_title.attr('data-selected', '49'); job_title.trigger('change'); break; case '067' : // fotografo user_role.attr('data-selected', 'LP'); user_role.trigger('change'); job_title.attr('data-selected', '54'); job_title.trigger('change'); break; case '068' : // nutrizionista user_role.val('LP').trigger('change'); job_title.attr('data-selected', '64'); job_title.trigger('change'); break; case '070' : // pet sitter user_role.attr('data-selected', 'LP'); user_role.trigger('change'); job_title.attr('data-selected', '69'); job_title.trigger('change'); break; default : break; } if(me.val() == '099'){ $('#activity_other').parent().removeClass('visually-hidden-focusable'); $('#activity_other').prop('required', true); } else{ $('#activity_other').parent().addClass('visually-hidden-focusable'); $('#activity_other').prop('required', false); } setMandatoryLabel(); }); $('#market_placement').on('change', function(e){ e.preventDefault(); let me = $(this); var m_p_o = $('#market_placement_other'); if(me.val() == '99'){ m_p_o.parent().removeClass('visually-hidden-focusable'); m_p_o.prop('required', true).val(''); } else{ m_p_o.parent().addClass('visually-hidden-focusable'); m_p_o.prop('required', false).val(''); } setMandatoryLabel(); }); $('#main_distribution_channel').on('change', function(e){ e.preventDefault(); let me = $(this); if(me.val() == '99'){ $('#main_distribution_channel_other').parent().removeClass('visually-hidden-focusable'); $('#main_distribution_channel_other').prop('required', true).val(''); } else{ $('#main_distribution_channel_other').parent().addClass('visually-hidden-focusable'); $('#main_distribution_channel_other').prop('required', false).val(''); } setMandatoryLabel(); }); $('input[name="sectors"]').on('change', function() { var $settore = $(this); var catCode = $settore.closest('.col-12').find('input[name="main_product_cat"]').val(); var $otherInput = $('#main_product_cat_other_' + catCode); // Se il settore NON checkato, resettiamo il campo di testo if (!$settore.is(':checked') && $settore.val() === '099') { if ($otherInput.length > 0) { $otherInput.val(''); // Svuota il testo $otherInput.removeClass('is-invalid is-valid'); // toglie lo stile $otherInput.siblings('.invalid-feedback').html(''); // Pulisce il messaggio } } }); $('#user_role').on('change', function(e){ e.preventDefault(); let me = $(this); let activity = $('#activity'); loadContattoJob(activity.val(), me.val()); }); $('#job_title').on('change', function(e){ e.preventDefault(); let me = $(this); if(me.val() == '099'){ $('#job_title_other').parent().removeClass('visually-hidden-focusable'); $('#job_title_other').prop('required', true).val(''); } else{ $('#job_title_other').parent().addClass('visually-hidden-focusable'); $('#job_title_other').prop('required', false).val(''); } setMandatoryLabel(); }); // invio form $form.on('submit', function(evt){ evt.preventDefault(); evt.stopPropagation(); let this_form = $(this); $btnSubmit.prop('disabled', true); // reset alert $('#alert_ok').addClass('d-none').find('h4').html(''); activeLoader(true); var sendData = this_form.serializeArray() || []; sendData.push({name:'method', value: 'save_visitors_form'}); sendData.push({name:'lang_real', value: jsLabelDictionary.lang_real}); sendData.push({name:'lang', value: jsLabelDictionary.lang}); var fd = new FormData(); $.each(sendData, function(i,v){ fd.append(v.name, v.value); }); $.ajax({ url: endpoint, type: 'POST', data: fd, contentType: false, cache: false, processData: false, dataType: 'json', success: function(response){ activeLoader(false); switch (response.code) { case 200 : case 201 : // tankyou message $('#alert_ok').removeClass('d-none').find('h4').html(response.message); // rimozione bottoni modal-footer $modal.find('.modal-footer').empty(); // aggiunta bottone chiudi $modal.find('.modal-footer').addClass('text-center'); let btnClose = $('').addClass('btn btn-speciale-fucsia').html(jsLabelDictionary.label_chiudi).on('click', function(e){ e.preventDefault(); $modal.modal('hide'); }); $modal.find('.modal-footer').append(btnClose); setTimeout(() => { $modal.modal('hide'); }, 5000); break; case 409 : // utente presente $('#alert_ok').removeClass('d-none').find('h4').html(response.message); //apri first accordion clickOnButtonAccordion(9); $btnSubmit.prop('disabled', false); break; case 500: default: // catch message $('#alert_ok').removeClass('d-none').find('h4').html(response.message); //apri first accordion clickOnButtonAccordion(9); $btnSubmit.prop('disabled', false); break; } }, error: function (request, status, error) { activeLoader(false); console.log(request, status, error); } }); }); // link presente nella modal error in caso di RE-registrazione e utente WEB_PENDING $('#modalError').on('click', '.resend-activation-email', function(e) { e.preventDefault(); var email = $(this).data('email'); $(this).prop('disabled', true); activeLoader(true); var sendData = []; sendData.push({name:'method', value: 'resend_visitor_email'}); sendData.push({name:'lang_real', value: jsLabelDictionary.lang_real}); sendData.push({name:'lang', value: jsLabelDictionary.lang}); sendData.push({name:'email', value: email}); var fd = new FormData(); $.each(sendData, function(i,v){ fd.append(v.name, v.value); }); // re invio della mail $.ajax({ url: endpoint, type: 'POST', data: fd, contentType: false, cache: false, processData: false, dataType: 'json', success: function(response){ if(response.code == '200'){ setTimeout(() => { activeLoader(false); window.location.href = '/'; }, 2000); } } }); // modifica il messaggio della modal }); //setMandatoryLabel(); loadCountry_and_telPrefix(); loadTipologia(); loadMerceologico(); loadTipologiaAllestimento(); loadQualiBuyerIncontrare(); loadMotivoRegistrazione(); }); /* ---------------------------------- ajax call to fill picklist ------------------------------------------------ */ async function loadNSalesPoints(typology){ try { var EL = $('#n_sales_point'); var selezionato = EL.data('value'); if(typology != ''){ const Response = await global_load_data('method=picklist_visitors&id_field=53&typology=' + typology); if(Response.code === 200 && Response.data.length > 0){ EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options).prop('required', true).parent().removeClass('visually-hidden-focusable'); $.each(Response.data, function(i,v){ let opt = $('').prop('value', v.code).html(v.name); if(v.code === selezionato){ opt.prop('selected', true); setTimeout(() => { EL.trigger('change'); }, 500); } EL.append(opt); }); } else{ EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options).prop('required', false).parent().addClass('visually-hidden-focusable'); } } else{ // manca parametro typology EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose + ' ' + jsLabelDictionary.label_tipologia); EL.append(options).prop('required', false).parent().addClass('visually-hidden-focusable'); } } catch(err) { console.log('err', err); } } async function loadMotivoRegistrazione(){ try { const Response = await global_load_data('method=picklist_visitors&id_field=48'); var EL = $('#motivo_reg'); var selezionato = EL.data('value'); if(Response.code === 200 && Response.data.length > 0){ EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options); if(Response.code === 200 && Response.data.length > 0){ $.each(Response.data, function(i,v){ let opt = $('').prop('value', v.code).html(v.name); if(v.code === selezionato){ opt.prop('selected', true); } EL.append(opt); }); if(editProfile){ // id edit rimuovo le 2 voci "espositore" dal motivo di registrazione $('#motivo_reg option[value="1"], #motivo_reg option[value="2"]').remove(); } } } } catch(err) { console.log('err', err); } } async function loadCountry_and_telPrefix(){ try { const Response = await global_load_data('method=picklist_visitors_country'); var EL = $('#country'); var ELprefix = $('#phone_prefix'); var selezionato = EL.data('value'); var selezionato2 = ELprefix.data('value'); if(Response.code === 200 && Response.data.length > 0){ EL.empty(); ELprefix.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose); var options3 = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options); ELprefix.append(options3); $.each(Response.data, function(i,v){ // country let opt = $('').prop('value', v.country).html(v.country_label); let real_number = '+' + v.country_phone_prefix; //.replace('00','+'); opt.attr('data-zone', (v.country_zone != '') ? v.country_zone : ''); opt.attr('data-prefix', real_number); opt.attr('data-blacklist', v.country_blacklist); if(v.country === selezionato){ opt.prop('selected', true); setTimeout(() => { EL.trigger('change'); }, 500); } EL.append(opt); // mobile_int_prefix let optPrefix = $('').val(real_number).html(v.country_label + ' (' + real_number + ')'); if(real_number === selezionato2){ optPrefix.prop('selected', true); } ELprefix.append(optPrefix); }); } } catch(err) { console.log('err', err); } } async function loadState(country){ try { var EL = $('#state'); var selezionato = EL.data('value'); if(country != ''){ const Response = await global_load_data('method=picklist_visitors_state' + country); EL.empty(); if(Response.code === 200 && Response.data.length > 0){ EL.prop('required', true).parent().removeClass('visually-hidden-focusable'); var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options); $.each(Response.data, function(i,v){ let opt = $('').prop('value', v.states).html(v.states_label); if(v.states === selezionato){ opt.prop('selected', true); } EL.append(opt); }); }else{ var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options).prop('required', false).parent().addClass('visually-hidden-focusable'); } setMandatoryLabel(); } else{ // manca parametro country EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options).prop('required', false).parent().addClass('visually-hidden-focusable'); } } catch(err) { console.log('err', err); } } async function loadTipologia(){ try { const Response = await global_load_data('method=picklist_visitors&show_visitors=1&id_field=10'); var EL = $('#tipology'); var selezionato = EL.data('value'); EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options); if(Response.code === 200 && Response.data.length > 0){ $.each(Response.data, function(i,v){ let opt = $('').prop('value', v.code).html(v.name); if(v.code === selezionato){ opt.prop('selected', true); setTimeout(() => { EL.trigger('change'); }, 500); } EL.append(opt); }); } } catch(err) { console.log('err loadTipologia', err); } } async function loadAttivita(typology){ try { var EL = $('#activity'); var selezionato = EL.data('value'); if(typology != ''){ const Response = await global_load_data('method=picklist_visitors&id_field=12&show_visitors=1&typology=' + typology); EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options); if(Response.code === 200 && Response.data.length > 0){ $.each(Response.data, function(i,v){ let opt = $('').prop('value', v.code).html(v.name); if(Response.data.length == 1){ opt.prop('selected', true); } if(v.code === selezionato){ opt.prop('selected', true); setTimeout(() => { EL.trigger('change'); }, 500); } EL.append(opt); }); if(Response.data.length == 1){ EL.trigger('change'); } } } else{ EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose + ' ' + jsLabelDictionary.label_tipologia); EL.append(options); } } catch(err) { console.log('err loadAttivita', err); } } async function loadDimAzienda(typology){ try { var EL = $('#company_size'); var selezionato = EL.data('value'); if(typology != ''){ const Response = await global_load_data('method=picklist_visitors&id_field=18&typology=' + typology); EL.empty(); if(Response.code === 200 && Response.data.length > 0){ var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options).prop('required', true).parent().removeClass('visually-hidden-focusable'); $.each(Response.data, function(i,v){ let opt = $('').prop('value', v.code).html(v.name); if(v.code === selezionato){ opt.prop('selected', true); setTimeout(() => { EL.trigger('change'); }, 500); } EL.append(opt); }); } else{ // non ci sono dati usando questa tipologia, viene nascosta quindi la picklist EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options).prop('required', false).parent().addClass('visually-hidden-focusable'); } } else{ EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose + ' ' + jsLabelDictionary.label_tipologia); EL.append(options).prop('required', false).parent().addClass('visually-hidden-focusable'); } } catch(err) { console.log('err loadDimAzienda', err); } } async function loadMainDistributionChannel(){ try { var EL = $('#main_distribution_channel'); var selezionato = EL.data('value'); EL.empty(); const Response = await global_load_data('method=picklist_visitors&id_field=20'); var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options); if(Response.code === 200 && Response.data.length > 0){ $.each(Response.data, function(i,v){ let opt = $('').prop('value', v.code).html(v.name); if(v.code === selezionato){ opt.prop('selected', true); setTimeout(() => { EL.trigger('change'); }, 500); } EL.append(opt); }); } else{ EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options); } } catch(err) { console.log('err loadMainDistributionChannel', err); } } // merceologico multiselect con checkbox async function loadMerceologico() { try { const Response = await global_load_data('method=picklist_visitors&id_field=14'); const EL = $('#main_product_cat'); let rawValue = String(EL.data('value') || ""); const selezionati = rawValue ? rawValue.split(',').map(v => v.trim()) : []; EL.empty(); if (Response.code === 200 && Response.data.length > 0) { // Caching dei puntatori DOM esterni al ciclo e all'evento const catAllEl = $('#main_product_cat_all'); const sectorsAllEl = $('#sectors_all'); $.each(Response.data, function(i, v) { let chk_item_row = $('').addClass('col-12 mb-3 border-bottom border-light closest-wrapper'); let chk_container = $('').addClass('form-check'); let chk_sector_container = $('').addClass('row sector-container ps-5'); // Aggiunto underscore per leggibilit e per evitare conflitti ID let idChk = 'main_product_cat_' + v.code; let chk = $('') .addClass('form-check-input') .prop({ type: 'checkbox', id: idChk, name: 'main_product_cat', value: v.code }); let chk_label = $('') .addClass('form-check-label') .prop('for', idChk) .text(v.name); let sector_container_invalid_feedback = $('') .addClass('invalid-feedback') .text(jsLabelDictionary.label_choose_at_least_one); chk_container.append(chk, chk_label); chk_item_row.append(chk_container, chk_sector_container, sector_container_invalid_feedback); EL.append(chk_item_row); // associo l'evento chk.on('change', async function() { let clicked = $(this); // Uso map() per generare direttamente l'array let main_product_catValues = $('input[name="main_product_cat"]:checked') .map((_, el) => el.value) .get(); catAllEl.val(main_product_catValues.join(',')); // Carica i settori await loadSettore(clicked); if (!clicked.is(':checked')) { // cerco il container genitore conosciuto clicked.closest('.col-12').find('input[name="sectors"]').prop('checked', false); } // Aggiorno il campo sectors_all let sectorsValues = $('input[name="sectors"]:checked') .map((_, el) => el.value) .get(); sectorsAllEl.val(sectorsValues.join(',')); }); // scateno il trigger per le preselezioni if (selezionati.includes(String(v.code))) { chk.prop('checked', true).trigger('change'); } }); } } catch(err) { console.error('err loadMerceologico', err); } } function updateSectorsAll() { const sectorsValues = $('input[name="sectors"]:checked').map(function() { return $(this).val(); }).get(); $('#sectors_all').val(sectorsValues.join(',')); } async function loadSettore(element_merceologico) { try { const $merceologico = $(element_merceologico); const $sector = $merceologico.closest('.closest-wrapper').find('.sector-container'); $sector.empty(); if (!$merceologico.is(':checked')) { updateSectorsAll(); // Pulisce i valori nel campo hidden se deselezionato return; } const payload = 'method=picklist_visitors&id_field=16&merceologico=' + encodeURIComponent($merceologico.val()); const Response = await global_load_data(payload); if (Response?.code === 200 && Array.isArray(Response.data) && Response.data.length > 0) { // i valori attuali salvati nel campo hidden e li metto in un array const savedSectorsRaw = $('#sectors_all').val() || ''; const savedSectorsArray = savedSectorsRaw.split(',').filter(Boolean); $.each(Response.data, function(i, v) { const baseId = $merceologico.val() + v.code; // se l'elemento corrente deve essere pre-selezionato const isCheckedDefault = savedSectorsArray.includes(baseId); // Generazione dei chk di settore let $chkItemRow = $('').addClass('col-md-3 col-12 mb-3'); let $chkContainer = $('').addClass('form-check form-check-inline'); let $chk = $('').addClass('form-check-input') .prop('type', 'checkbox') .prop('id', 'sectors_' + baseId) .prop('name', 'sectors') .prop('value', baseId) .prop('checked', isCheckedDefault); // Imposto lo stato checked iniziale let $chkLabel = $('').addClass('form-check-label') .prop('for', 'sectors_' + baseId) .html(v.name); $chkContainer.append($chk, $chkLabel); $chkItemRow.append($chkContainer); $sector.append($chkItemRow); // Generazione campo 'altro' SOLO se il settore 099 if (v.code === '099') { let $chkItemRowAltro = $('').addClass('col-12 mb-3'); // Operatore ternario per rimuovere la classe hidden se pre-selezionato let visibilityClass = isCheckedDefault ? 'mb-3 soft' : 'mb-3 soft visually-hidden-focusable'; let $chkItemContainerAltro = $('').addClass(visibilityClass); let $chkLabelAltro = $('').prop('for', 'main_product_cat_other_' + $merceologico.val()).html(jsLabelDictionary.label_fornisci_ulteriori_dettagli); let $iText = $('').addClass('form-control').prop('type', 'text').prop('maxlength', '255').prop('id', 'main_product_cat_other_' + $merceologico.val()).prop('name', 'main_product_cat_other_' + $merceologico.val()); // Se pre-selezionato, imposto il required di default if (isCheckedDefault) $iText.prop('required', true); let $chkItemFeedbackAltro = $('').addClass('invalid-feedback').html(jsLabelDictionary.label_insert_valid_text); $chkItemContainerAltro.append($chkLabelAltro, $iText, $chkItemFeedbackAltro); $chkItemRowAltro.append($chkItemContainerAltro); $sector.append($chkItemRowAltro); // Binding isolato per logica "Altro" $chk.on('change', function() { if ($(this).is(':checked')) { $chkItemContainerAltro.removeClass('visually-hidden-focusable'); $iText.prop('required', true); // Rimosso il .val('') qui. } else { $chkItemContainerAltro.addClass('visually-hidden-focusable'); $iText.prop('required', false).val(''); } if (typeof setMandatoryLabel === 'function') setMandatoryLabel(); }); } // Binding generale per aggiornamento campo hidden $chk.on('change', function() { updateSectorsAll(); }); // Se c' un solo elemento, evito di rilanciare il trigger se gi pre-selezionato if (Response.data.length === 1 && !isCheckedDefault) { $chk.prop('checked', true).trigger('change'); } }); } } catch(err) { console.error('Errore loadSettore:', err); } } async function loadAreaGeograficaTrattata(){ try { const Response = await global_load_data('method=picklist_visitors&id_field=22'); var EL = $('#covered_markets'); //var EL1 = $('#what_market'); let rawValue = String(EL.data('value') || ""); const selezionato = rawValue ? rawValue.split(',').map(v => v.trim()) : []; //var listaValori1 = EL1.data('value') || []; //const selezionato1 = listaValori1.split(',').map(v => v.trim()); EL.empty(); if(Response.code === 200 && Response.data.length > 0){ $.each(Response.data, function(i,v){ let chk_item_row = $('').addClass('col-md-4 col-12 mb-2'); let chk_container = $('').addClass('form-check form-check-inline'); let chk = $('').addClass('form-check-input').prop('type', 'checkbox').prop('id', 'covered_markets' + v.code).prop('name', 'covered_markets').prop('value', v.code); let chk_label = $('').addClass('form-check-label').prop('for', 'covered_markets' + v.code).text(v.name); if (selezionato.includes(String(v.code))) { chk.prop('checked', true); } chk_container.append(chk, chk_label); chk_item_row.append(chk_container); EL.append(chk_item_row); }); /* $.each(Response.data, function(i,v){ let chk_item_row = $('').addClass('col-md-4 col-12 mb-2'); let chk_container = $('').addClass('form-check form-check-inline'); let chk = $('').addClass('form-check-input').prop('type', 'checkbox').prop('id', 'what_market' + v.code).prop('name', 'what_market').prop('value', v.code); let chk_label = $('').addClass('form-check-label').prop('for', 'what_market' + v.code).html(v.name); if(selezionato1.includes(v.code)){ chk.prop('checked', true); } chk_container.append(chk, chk_label); chk_item_row.append(chk_container); EL1.append(chk_item_row); });*/ } } catch(err) { console.log('err loadAreaGeograficaTrattata', err); } } async function loadTipologiaAllestimento(){ try { const Response = await global_load_data('method=picklist_visitors&id_field=25'); var EL = $('#type_setup'); var selezionato = EL.data('value'); EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options); if(Response.code === 200 && Response.data.length > 0){ $.each(Response.data, function(i,v){ let opt = $('').prop('value', v.code).html(v.name); if(v.code === selezionato){ opt.prop('selected', true); setTimeout(() => { EL.trigger('change'); }, 500); } EL.append(opt); }); } } catch(err) { console.log('err loadTipologiaAllestimento', err); } } async function loadQualiBuyerIncontrare(){ try { const Response = await global_load_data('method=picklist_visitors&id_field=10&show_buyer=1'); var EL = $('#which_buyers_meet'); var selezionato = EL.data('value'); EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options); if(Response.code === 200 && Response.data.length > 0){ $.each(Response.data, function(i,v){ let opt = $('').prop('value', v.code).html(v.name); if(v.code === selezionato){ opt.prop('selected', true); setTimeout(() => { EL.trigger('change'); }, 500); } EL.append(opt); }); } } catch(err) { console.log('err loadQualiBuyerIncontrare', err); } } async function loadMarketPlacement(){ try { const Response = await global_load_data('method=picklist_visitors&id_field=54'); var EL = $('#market_placement'); var selezionato = EL.data('value'); EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options); if(Response.code === 200 && Response.data.length > 0){ $.each(Response.data, function(i,v){ let opt = $('').prop('value', v.code).html(v.name); if(v.code === selezionato){ opt.prop('selected', true); setTimeout(() => { EL.trigger('change'); }, 500); } EL.append(opt); }); } } catch(err) { console.log('err loadQualiBuyerIncontrare', err); } } async function loadRuoloContatto(tipologia){ try { var EL = $('#user_role'); var selezionato = EL.data('value'); if(tipologia != ''){ const Response = await global_load_data('method=picklist_visitors&id_field=31&typology=' + tipologia); EL.empty(); if(Response.code === 200 && Response.data.length > 0){ var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options).prop('required', true); $.each(Response.data, function(i,v){ let opt = $('').prop('value', v.code).html(v.name); if(tipologia == '14'){ if(v.code == 'LP'){ opt.removeAttr('disabled').prop('selected', true); } } if(v.code === selezionato){ opt.prop('selected', true); setTimeout(() => { EL.trigger('change'); }, 500); } EL.append(opt); }); } else{ // non ci sono dati usando questa tipologia, viene nascosta quindi la picklist EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options).prop('required', false); } } else{ EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose + ' ' + jsLabelDictionary.label_tipologia); EL.append(options).prop('required', false); } } catch(err) { console.log('err loadRuoloContatto', err); } } async function loadContattoJob(attivita, ruolo){ try { var EL = $('#job_title'); var selezionato = EL.data('value'); if(attivita != '' && ruolo != ''){ const Response = await global_load_data('method=picklist_visitors&id_field=32&show_visitors=1&activity=' + attivita + '&role=' + ruolo); EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options); if(Response.code === 200 && Response.data.length > 0){ $.each(Response.data, function(i,v){ let opt = $('').prop('value', v.code).html(v.name); if(v.code === selezionato){ opt.prop('selected', true); setTimeout(() => { EL.trigger('change'); }, 500); } EL.append(opt); }); } else{ EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_no_job_for_this_activity_and_role); EL.append(options); } } else{ EL.empty(); var options = $('').val('').html(jsLabelDictionary.label_choose); EL.append(options); } } catch(err) { console.log('err loadContattoJob', err); } } async function check_email_visitor(email){ try { const Response = await global_load_data('method=check_visitor_email&email=' + email); if(Response.code === 200){ return Response.message; } else{ return false; } } catch(err) { console.log('err check_visitor_email', err); } } /* ---------------------------------- end ajax call to fill picklist ------------------------------------------------ */ /* Funzione chiamata globale ajax * @parametri parametri concatenati da & * che vengono inviati in POST */ async function global_load_data(parametri){ parametri += '&lang=' + jsLabelDictionary.lang; // 1. controller per gestire l'interruzione const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 5000); // Imposta un timeout di 5 secondi try { const response = await fetch(endpoint, { method: 'POST', body: parametri, headers: {'Content-type': 'application/x-www-form-urlencoded'}, signal: controller.signal }); clearTimeout(timeoutId); const data = await response.json(); return data; } catch (error) { clearTimeout(timeoutId); if (error.name === 'AbortError') { console.error("La richiesta stata annullata per timeout (5 secondi)."); throw new Error("Timeout della richiesta."); } throw error; } } /* -------------------------------------------------------------------------------------------------------- * -------------------------------------------------------------------------------------------------------- * Funzione di validazione blocco accordion * @step indice dell'accordion da validare (il primo e' 1) * -------------------------------------------------------------------------------------------------------- * -------------------------------------------------------------------------------------------------------- */ async function validateSection(step){ var returnCheck = true; return new Promise(async (resolve, reject) => { // controllo sui campi required const selectors = 'input[required]:not([type="radio"]):not([type="checkbox"]), select[required], textarea[required]'; //const selectors = 'input[required], select[required], textarea[required]'; let acc_controls; //console.log('validateSection -> acc_controls', acc_controls) switch (step) { case 9 : // Perch Zoomark? acc_controls = $('#collapse' + step).find(selectors); acc_controls.each(function() { const $field = $(this); const fieldId = $field.attr('id'); const fieldValue = $.trim($field.val()); // Rimuove spazi vuoti accidentali // Controllo validit: gestiamo sia il vuoto che il null if (!fieldValue || fieldValue === '') { setInvalidateField(fieldId, jsLabelDictionary.label_This_field_is_required); returnCheck = false; } else{ setValidateField(fieldId); } }); break; case 10 : // Il tuo account // controllo se utente esistente e status = WEB_ACTIVE solo insert if(!editProfile){ const emailValue = $('#email').val(); var resultCheckEmail = await check_email_visitor(emailValue); if (resultCheckEmail) { $('#modal_visitor_register').modal('hide'); $('#modal_visitor_register').one('hidden.bs.modal', function(e) { $('#modalError').find('.modal-body').html(resultCheckEmail); $('#modalError').modal('show'); }); returnCheck = false; } } acc_controls = $('#collapse' + step).find(selectors); acc_controls.each(function() { const $field = $(this); const fieldId = $field.attr('id'); const fieldValue = $.trim($field.val()); // Rimuove spazi vuoti accidentali // Controllo validit: gestiamo sia il vuoto che il null if (!fieldValue || fieldValue === '') { setInvalidateField(fieldId, jsLabelDictionary.label_This_field_is_required); returnCheck = false; } else{ setValidateField(fieldId); } }); // controllo semantico email var emailField = $('#email').val(); if($.trim(emailField) != '' && !regex_email_valida.test(emailField)){ setInvalidateField('email', jsLabelDictionary.g_label_email_not_correct); returnCheck = false; } else if($.trim(emailField) != ''){ setValidateField('email'); } if(!editProfile){ // controllo per le password var passwordField = $('#password').val(); var passwordConfirmField = $('#password_confirm').val(); // Validazione campo Password principale if($.trim(passwordField) != '' && !regex_password_valida.test(passwordField)){ setInvalidateField('password', jsLabelDictionary.label_validate_password_message); returnCheck = false; } else if($.trim(passwordField) != ''){ setValidateField('password'); } // Validazione campo Conferma Password (controllo uguaglianza) if($.trim(passwordConfirmField) != '' && passwordConfirmField !== passwordField){ setInvalidateField('password_confirm', jsLabelDictionary.gate_err_eqpswd); returnCheck = false; } else if($.trim(passwordConfirmField) != '' && passwordConfirmField === passwordField){ setValidateField('password_confirm'); } } break; case 1 : // La tua azienda //var CEEzone = $('#country option:selected').attr('data-zone'); var CEEzone = $('#country').val(); var piva = $('#vat').val().toUpperCase().replace(/\s/g, ''); var cf = $('#cod_fiscale').val().toUpperCase().replace(/\s/g, ''); //if(CEEzone === 'CEE'){ if(CEEzone === 'ITALIA'){ if(piva == '' && cf == ''){ // Se nessuno dei due campi compilato returnCheck = false; setInvalidateField('vat', jsLabelDictionary.label_vat_taxcode_required); setInvalidateField('cod_fiscale', jsLabelDictionary.label_vat_taxcode_required); } else{ // Almeno uno compilato, validazione del formato // Inizializza i campi come validi, saranno invalidati se falliscono il formato setValidateField('vat'); setValidateField('cod_fiscale'); if (piva !== '') { // Se la Partita IVA compilata e NON rispetta il formato generico if (!pivaGenericRegex.test(piva)) { returnCheck = false; setInvalidateField('vat', jsLabelDictionary.label_error_partita_iva); } $('#cod_fiscale').prop('required', false); } if (cf !== '') { // Se il Codice Fiscale compilato e NON rispetta la struttura if (!cfRegex.test(cf)) { returnCheck = false; setInvalidateField('cod_fiscale', jsLabelDictionary.label_error_codice_fiscale); } $('#vat').prop('required', false); } setMandatoryLabel(); } } else{ // solo aziende estere if (piva !== '') { // Se la Partita IVA compilata e NON rispetta il formato generico if (!pivaGenericRegex.test(piva)) { returnCheck = false; setInvalidateField('vat', jsLabelDictionary.label_error_partita_iva); } $('#cod_fiscale').prop('required', false); setMandatoryLabel(); } } const websiteField = $('#website').val().trim(); if (websiteField !== '') { if (!isValidHttpUrl(websiteField)) { setInvalidateField('website', jsLabelDictionary.label_web_social_help_text); returnCheck = false; } else { setValidateField('website'); } } else { setValidateField('website'); } // Controlla se i 2 radio sono required const target_giornalista = $('input[name="target_giornalista"]'); const isGroupChecked = target_giornalista.is(':checked'); target_giornalista.each(function() { const $f = $(this); const fId = $f.attr('id'); const isRequired = $f.prop('required'); if (isRequired) { if (isGroupChecked) { setValidateField(fId); } else { setInvalidateField(fId, jsLabelDictionary.label_This_field_is_required); returnCheck = false; } } }); // dopo controlli generici acc_controls = $('#collapse' + step).find(selectors); acc_controls.each(function() { const $field = $(this); const fieldId = $field.attr('id'); const fieldValue = $.trim($field.val()); // Rimuove spazi vuoti accidentali // Controllo validit: gestiamo sia il vuoto che il null (tipico delle select) if (!fieldValue || fieldValue === '') { setInvalidateField(fieldId, jsLabelDictionary.label_This_field_is_required); returnCheck = false; } else{ setValidateField(fieldId); } }); break; case 2 : // La tua attivita acc_controls = $('#collapse' + step).find(selectors); acc_controls.each(function() { const $field = $(this); const fieldId = $field.attr('id'); const fieldValue = $.trim($field.val()); // Rimuove spazi vuoti accidentali // Controllo validit: gestiamo sia il vuoto che il null (tipico delle select) if (!fieldValue || fieldValue === '') { setInvalidateField(fieldId, jsLabelDictionary.label_This_field_is_required); console.log('la tua azienda -> ', fieldId, ' vuoto o null') returnCheck = false; } else{ setValidateField(fieldId); } }); // lista di chk covered_markets // se non visibili non sono da validare if (!$('#covered_markets').parent().hasClass('visually-hidden-focusable')){ var checkboxes = $('input[name="covered_markets"]'); var containerID = 'covered_markets'; // Verifica se almeno una selezionata if (checkboxes.filter(':checked').length === 0) { // Passiamo l'ID del contenitore per colorare l'area o mostrare l'errore setInvalidateField(containerID, jsLabelDictionary.label_is_invalid_covered_markets_MSG); checkboxes.addClass('is-invalid'); returnCheck = false; } else { // Se almeno una selezionata, validiamo il campo setValidateField(containerID); checkboxes.removeClass('is-invalid'); } // Rimuove l'errore al click checkboxes.on('change', function() { if (checkboxes.filter(':checked').length > 0) { setValidateField(containerID); checkboxes.removeClass('is-invalid'); } }); } break; case 8: // A cosa sei interessato acc_controls = $('#collapse' + step).find(selectors); $.each(acc_controls, function(i,v){ if($(v).val() == ''){ setInvalidateField($(v).prop('id'), jsLabelDictionary.label_This_field_is_required); returnCheck = false; } else{ setValidateField($(v).prop('id')); } }); var checkboxes = $('input[name="main_product_cat"]'); var containerID = 'main_product_cat'; if (checkboxes.filter(':checked').length === 0) { // Nessuna merceologia selezionata: errore generico sul contenitore setInvalidateField(containerID, jsLabelDictionary.label_select_at_least_one_main_prod_cat_MSG); returnCheck = false; } else { // Puliamo l'errore generico se presente setValidateField(containerID); checkboxes.filter(':checked').each(function() { var chkSel = $(this); var catCode = chkSel.val(); // A, B, Z... var catID = chkSel.attr('id'); // Cerchiamo i settori selezionati in questa categoria var $settoriSelezionati = chkSel.closest('.col-12').find('input[name="sectors"]:checked'); if ($settoriSelezionati.length === 0) { setInvalidateField(catID, jsLabelDictionary.label_select_at_least_one_sector_MSG); returnCheck = false; } else { setValidateField(catID); // Controllo dinamico "Altro" per ogni settore 099 $settoriSelezionati.each(function() { var $settore = $(this); // Se il valore del settore 099, verifichiamo il campo di testo collegato if ($settore.val() === '099') { var $otherInput = $('#main_product_cat_other_' + catCode); if ($otherInput.length > 0 && $.trim($otherInput.val()) === "") { setInvalidateField($otherInput.attr('id'), jsLabelDictionary.label_select_at_sector_other_MSG); returnCheck = false; } else if ($otherInput.length > 0) { setValidateField($otherInput.attr('id')); } } }); } }); } break; case 6: // Privacy policy if(!$('#privacy01').is(':checked')){ setInvalidateField('privacy01', jsLabelDictionary.label_This_field_is_required); returnCheck = false; } break; default : returnCheck = false; break; } $('#head_button_' + step).prop('disabled', returnCheck); resolve(returnCheck); }); } /* * Impostazione di interfaccia validata su checkbox multichoice */ function setValidateMultiChoice(EL, merceologico){ const thisField = $('#' + EL); thisField.parent().find('.invalid-feedback').css('display', 'none'); } /* * Impostazione di interfaccia NON validata su checkbox multichoice */ function setInvalidateMultiChoice(EL, _errMsg, merceologico){ // merceologico e' una lettera const thisField = $('#' + EL); let errMsg = _errMsg || ''; // validazione di tutti i campi multichoiche non aggiunti thisField.parent().find('.invalid-feedback').css('display', 'block'); if(errMsg.length > 0){ thisField.parent().find('.invalid-feedback').html(errMsg); } } /* * INvalida un controllo decorandolo via css * @ EL string id del controllo da invalidare * @ _errMsg messaggio custom che si intende visualizzare * nella sezione helptext * return void */ function setInvalidateField(EL, _errMsg) { const thisField = $('#' + EL); const thisAccordionItem = thisField.closest('.accordion-item'); const thisStepButton = thisAccordionItem.find('.accordion-button'); const thisStep = thisField.closest('.accordion-body'); let errMsg = _errMsg || ''; if(errMsg.length > 0){ thisField.parent().find('.invalid-feedback').show().html(errMsg); } // Stato invalido thisStepButton.addClass('is-invalid'); thisField.addClass('is-invalid'); // Rimuoviamo eventuali listener precedenti per evitare duplicazioni thisField.off('focus.cleanup').on('focus.cleanup', function() { $(this).removeClass('is-invalid'); // Verifichiamo se ci sono altri errori nello STESSO step // Se non ce ne sono pi, puliamo il bottone dell'accordion if (thisStep.find('.is-invalid').length === 0) { thisStepButton.removeClass('is-invalid'); thisStep.find('button.btn-nav').prop('disabled', false); $('.alert_section').addClass('d-none'); } }); } /* * decorazione di un campo validato * @EL string id del campo da validare * return void */ function setValidateField(EL) { const thisField = $('#' + EL); const thisStep = thisField.closest('.accordion-body'); const thisAccordionItem = thisField.closest('.accordion-item'); const thisStepButton = thisAccordionItem.find('.accordion-button'); // Stato del campo: rimuove l'errore e aggiunge il successo thisField.removeClass('is-invalid').addClass('is-valid'); // Pulizia del feedback testuale (se presente) thisField.closest('[class*="col-"]').find('.invalid-feedback').html('').hide(); // Controllo dello stato dello step (accordion) // Verifichiamo se ci sono ancora elementi invalidi in tutto il corpo dell'accordion if (thisStep.find('.is-invalid').length === 0) { // Rimuove lo stato di errore dal bottone dell'header thisStepButton.removeClass('is-invalid'); // dare un feedback positivo anche all'accordion header // thisStepButton.addClass('is-valid'); // Abilita il bottone di navigazione "Avanti" thisStep.find('button.btn-nav').prop('disabled', false); } } /* * passa all'accordion precedente * @p id precedente * @n id successivo * @t id this * return void */ function stepBack(p,n,t){ clickOnButtonAccordion(p); } /* valida sezione e * passa all'accordion successivo * @p id precedente * @n id successivo * @t id this * return void */ async function stepForward(p,n,t){ await validateSection(t).then(risultato => { var alert_section = $('#alert_section_' + t); // nasconde gli alert di sezione alert_section.addClass('d-none'); if(risultato){ // se la sezione e' stata validata ed e' passata alla successiva, // pulisce eventuali campi in errori della sezione attuale $('#collapse' + p + ' textarea').removeClass('is-invalid'); $('#collapse' + p + ' input').removeClass('is-invalid'); $('#collapse' + p + ' select').removeClass('is-invalid'); var acc_controls = $('#collapse' + n + ' input[required], #collapse' + n + ' select[required]'); acc_controls.first().trigger('focus'); clickOnButtonAccordion(n); } else{ alert_section.removeClass('d-none'); } }); } /* * Imposta dinamicamente gli asterischi sui campi contrassegnati con * la prop required * return void */ function setMandatoryLabel(){ $form.find('label').removeClass('mandatory'); $form.find('textarea[required]').parent().parent().find('label').addClass('mandatory'); $form.find('input[required]').parent().parent().find('label').addClass('mandatory'); $form.find('select[required]').parent().parent().find('label').addClass('mandatory'); } /* * Click sul bottone di ogni accordion * @ stepNow integer indice accordion da attivare * return void */ function clickOnButtonAccordion(stepNow) { // ID visitors-accordion-item-X const targetAccordionItem = $('#visitors-accordion-item-' + stepNow); // Pulizia totale degli stati (Errori e Successi) // Rimuoviamo le classi dagli input, select e dal bottone header targetAccordionItem.find('.is-invalid, .is-valid, .valid, .is-invalid').removeClass('is-invalid is-valid valid'); // Rimuoviamo eventuali classi custom dai wrapper (come 'has-success') targetAccordionItem.find('.has-success, .has-error').removeClass('has-success has-error'); // Svuotiamo i messaggi di errore testuali targetAccordionItem.find('.invalid-feedback').html(''); // Sblocchiamo il bottone dell'header se era disabilitato e simuliamo il click $('#visitors_head_button_' + stepNow).not('.btn-nav').prop('disabled', false).trigger('click'); setTimeout(() => { // Uso lo stesso ID della struttura per lo scroll scrollToTarget('visitors-accordion-item-' + stepNow); }, 1200); } function setInvalidateMultiselect(EL, _errMsg) { const thisField = $('#' + EL); const thisStep = thisField.closest('.accordion-body'); const thisAccordionItem = thisField.closest('.accordion-item'); const thisStepButton = thisAccordionItem.find('.accordion-button'); let errMsg = _errMsg || ''; // Gestione Messaggio Errore // Risaliamo alla colonna o al parent comune per trovare l'invalid-feedback const errorContainer = thisField.closest('[class*="col-"]').find('.invalid-feedback'); if(errMsg.length > 0){ errorContainer.html(errMsg).show(); } // Stato invalido sull'Accordion Header thisStepButton.addClass('is-invalid'); // Stato invalido sul Bottone del Multiselect // Solitamente il multiselect crea un bottone come fratello o figlio del parent const multiselectBtn = thisField.parent().find('button.multiselect, button.dropdown-toggle'); multiselectBtn.addClass('is-invalid').off('click.cleanup').on('click.cleanup', function(e) { $(this).removeClass('is-invalid'); errorContainer.hide(); // Aspettiamo un attimo per il ricalcolo degli errori rimasti setTimeout(() => { if (thisStep.find('.is-invalid').length === 0) { thisStepButton.removeClass('is-invalid'); // Sblocca i bottoni di navigazione (btn-nav o af_step) thisStep.find('.btn-nav, .af_step').prop('disabled', false); } }, 100); }); } function isValidHttpUrl(urlString) { try { const url = new URL(urlString); return url.protocol === "http:" || url.protocol === "https:"; } catch (err) { return false; } }