javascriptjquerydatepickerclonehubspot

Hubspot date picker clone using Jquery not working


I'm making an application form using hubspot and adding an "add+" button to allow the user to add additional education and experience fields. When I clone the fields using jquery, the date fields are no longer functioning. How can I reinitialize the fields or make the cloned fields recognize the date picker? Thanks in advance!

openModal() {

// Set form submit to allow for multiple applications
this.formSubmitted = false;
this.isModalOpen = true;
document.documentElement.style.overflow = 'hidden';

// Create hubspot form on modal open to allow for multiple applications
hbspt.forms.create({
  region: "na1",
  portalId: "",
  formId: "",
  target:".hubspot-form-area",
  onFormSubmitted: function($form){
    applicationModal.formSubmitted = true;
  },
  onFormReady: ($form) => {

    // Display file name on hubspot file upload
    $('.hs-fieldtype-file input').on('change', function() {
      const fileName = $(this).val().split('\\').pop();
      const spanElement = $(this).parent().parent().find('label > span');
      spanElement.text(fileName || 'File has been uploaded!');

    });

    function addFieldsClick(...fields) {
      return function(e) {
        e.preventDefault();


        let clonedFields = [];

        // Clone each field, clear its value
        fields.forEach(function(field, index) {
          let lastField = $(`.hubspot-form-area ${field}:last`);
          let clonedField = lastField.clone();
          clonedField.find('input').val('');


          // Check if the element has the class .form-columns-2 and apply the appropriate display property
          if (clonedField.is('.form-columns-2')) {
            clonedField.css('display', 'flex');

          } else {
            clonedField.css('display', 'block');
          }

          clonedFields.push(clonedField);
        });

        // Add the remove button
        let removeBtn = $('<fieldset class="form-columns-0"><div class="hs-richtext hs-main-font-element"><span class="trashcan-icon"><img src="/trashcan" class="remove-education" alt="Trash Can Icon"/></span></div></fieldset>');
        removeBtn.find('.remove-education').click(function(f) {
          f.preventDefault();

          // Remove the cloned fields and the remove button
          clonedFields.forEach(function(clonedField, index) {
            clonedField.remove();
          });

          removeBtn.remove();
        });

        // Append the cloned fields and the remove button to the last field of the last type
        let lastFieldOfLastType = $(`.hubspot-form-area ${fields[fields.length - 1]}:last`);
        lastFieldOfLastType.after(removeBtn);
        clonedFields.reverse().forEach(function(clonedField, index) {
          removeBtn.after(clonedField);
        });
      };
    }

    $('.add-education.first-add').off('click').click(addFieldsClick('.form-columns-1:has(.hs_school)', '.form-columns-1:has(.hs_field_of_study)', '.form-columns-1:has(.hs_degree)', '.form-columns-2:has(.hs_school_start_date_)'));
    $('.add-education.second-add').off('click').click(addFieldsClick('.form-columns-1:has(.hs_jobtitle)', '.form-columns-1:has(.hs_company)', '.form-columns-1:has(.hs_0-2\\/industry)', '.form-columns-1:has(.hs_experience_summary__optional__)', '.form-columns-2:has(.hs_job_start_date)', '.form-columns-1:has(.hs_i_currently_work_here_single_checkbox)'));

  },
});
},

I tried using the jquery datepicker function but it doesnt seem to work with hubspot


Solution

  • You should never, ever use JQuery with Vue.

    Unless you absolutely have to, and here's an article outlining that nightmare: https://medium.com/js-dojo/how-to-safely-use-a-jquery-plugin-with-vue-js-786acdfb743b.

    However, it sounds like you found a date picker for JQuery, and figured you could use it for Vue. Instead, you need to find a date-picker for vue.

    I don't know what version of Vue you're using, but here's a Date-Picker for Vue3: https://vue3datepicker.com/


    In case you're interested, here's why you shouldn't use a JQuery Plug-in with Vue.

    First I'll discuss a little history of web development to show the relationship of JQuery and Single-page web app frameworks (We'll call these SWAFs for short) like Vue, React and Angular. And once we know the difference, I'll explain why they should not be used together.

    JQuery is a precursor to SWAFs. Before SWAFs, JQuery would make changes directly to the live DOM.

    And that was a huge breakthrough, but it also compensated for the differences between browsers (at the time Microsoft's IE did not follow standardized protocol for how javascript works). And that was also an invaluable tool.

    Since then, IE has all but gone extinct - especially in consumer computers. And we don't have to worry as much about the differences between how browsers interpret JavaScript.

    But more importantly, as people built great things with JQuery, the code started getting way too complex to be reasonably manageable. About that time, some big companies started realizing this, and began building ways to make the complexity more manageable.

    Google built Angular, and a bit later Facebook built React. Then a bit later, This guy called "Evan You" realized there was a lot of stuff in those frameworks that were great for big companies, but bad for smaller projects, so he built a more efficient, stripped down framework called Vue.

    The important thing to know about that whole thing is that Angular, React and Vue all work basically the same way, and they improved on what JQuery was already doing.

    So think about this JQuery-based web app:

    <!-- index.html -->
    <form>
      <input type="text"/> 
      <button type="submit">Submit</button>
    </form>
    
    // actions.js
    $(document).ready(()=>$(button).on('click',checkValue())
    
    // validate.js
    function checkValue(){
      if($('input').attr('value')===''){
        alert('No value')
        return false
      } else {
        $('form').html('<div>Success!!</div>')
      }
    }
    
    

    In this app, the user fills out some data, presses submit, then JQuery changes the content on the page to show "Success!!"

    Now take a look at how a SWAF would be different:

    <!-- index.html -->
    <Form/>
    
    
    // Form.js
    
    let success = false
    
    function Form(){
      return {
        <form>
          success ? Success!! :
          {
            <input type="text"/> 
            <button type="submit" onclick="checkValue()">Submit</button>
          }
        </form>
      }
    }
    
    function checkValue(){
      if(state.input.value==='')
        alert('No value')
      else 
        success = true
    }
    

    See how SWAFs use that thing called "state." That variable replaces JQuery. It holds all the elements on the page, so you make changes to that, then it pushes those changes to the page (that process is called rendering).

    So JQuery updates the live DOM, whereas SWAFs update a virtual DOM. So when you mix the two, the best case is the JQuery gets overwritten mysteriously, the worst case is you make it work for a while, then it stops working all the sudden and you have no idea why.