Skip to content

Capture form submit to fire custom request

Mikk Pristavka edited this page Nov 28, 2017 · 2 revisions
document.querySelector('form').addEventListener('submit', function(event) {
  event.preventDefault();
  var form = event.target;
  var fields = $(event.target).serialize() // this is why jQuery is necessary in this example
    .split('&')
    .map(decodeURIComponent)
    .map(function(f) { return f.split('=')}
  ); // array of [fieldname, fieldvalue]

  var formData = fields.reduce(function(acc, field) {
    // strip unnecessary parts to find the field ID
    var fieldID = field[0]
      .replace('ticket[data][', '')
      .replace('ticket[', '')
      .replace(']', '');
    // find the label element for the given ID
    var fieldLabel = document.querySelector('label[for="field_' + fieldID + '"]');
    
    // if label exists, add its contents as the key and the field's value as the value
    if (fieldLabel) {
      acc[fieldLabel.textContent] = field[1];
    }
    return acc;
  }, {});
   
  // example: Google Tag Manager event with callback
  dataLayer.push(Object.assign({}, formData, {
    'event' : 'myevent',
    'eventCallback' : function() {
       form.submit(); // submit the form after the request is completed
    }
  }));
})

Clone this wiki locally