jeudi 2 décembre 2021

How to use an if statement to only collect forms fields that contain an '@' symbol in?

I'm currently collecting form abandonments from my website using the javascript code below within tag manager of an analytics software (Piwik pro).

It currently works great, however I'm now trying to make it so that only emails with an '@' collect and nothing else.

I'm thinking that an if statement that has .includes("@") will do the job, however as I'm a beginner and I did not write this code, I am struggling to make it work. The below shows what I've tried (amongst many other attempts) and it either continues to collect everything, or doesn't collect anything...

(Also im unsure if _paq.push is used outside of the analytics software I use, but that line creates a custom event within piwik pro.)

formFields = ['input_3_1','input_3_2','input_3_3','input_3_4']

  let formFieldText = document.getElementById('input_3_1').value
  let fieldHasAtSymbol = formFieldText.includes("@")
  
  if (fieldHasAtSymbol = 'true') {

        function trackUnsubmittedField(fieldId){
          let formField = document.getElementById(fieldId)
          if(formField.nodeName==="SELECT"){
            formField.addEventListener('change',()=>{
              _paq.push(['trackEvent','formAbandonment',fieldId,document.getElementById(fieldId).value])
            })
          }
          else{
            formField.addEventListener('focusout',()=>{
                _paq.push(['trackEvent','formAbandonment',fieldId,document.getElementById(fieldId).value])
            })
          }
        }
  }
        formFields.map(element=>trackUnsubmittedField(element))

I've also tried using the same formField variable that's declared within the function by placing an .includes() if statement within it, but no luck.

formFields = ['input_3_1','input_3_2','input_3_3','input_3_4']

        function trackUnsubmittedField(fieldId){
          let formField = document.getElementById(fieldId)
          
                if (formField.includes("@") = "true") {
          
          if(formField.nodeName==="SELECT"){
            formField.addEventListener('change',()=>{
              _paq.push(['trackEvent','formAbandonment',fieldId,document.getElementById(fieldId).value])
            })
          }
          else{
            formField.addEventListener('focusout',()=>{
                _paq.push(['trackEvent','formAbandonment',fieldId,document.getElementById(fieldId).value])
            })
                }
        }
  
        formFields.map(element=>trackUnsubmittedField(element))

There's probably lots wrong with the code i added onto this but any help would be appreciated, thank you!

Aucun commentaire:

Enregistrer un commentaire