user14484722
user14484722

Reputation: 77

GTM - tracking latest input click value

My script

function() {
  var inputs = document.getElementsByTagName("input"),
      selectedRadios = [];
  for (var i = 0;i < inputs.length;i++) {
    if(inputs[i].type==="checkbox" && inputs[i].checked) {
      selectedRadios.push(inputs[i].value);
    }
  }
  return selectedRadios;
} 

This script returns an array of all the checked buttons value. So, in my case, if I check three inputs the array will be for example: [167,168,169]

Issue: The array is auto sorted in ascending numerical order, while I want that the array is sorted based on which one was checked first, second, third,... .

To do that I edited the script above in this way

function() {
  var inputs = document.getElementsByTagName("input"),
      selectedRadios = [],
      selectedRadios_latestchoice = [];

  // get all checkboxs selected
  for (var i = 0;i < inputs.length;i++) {
    if(inputs[i].type==="checkbox" && inputs[i].checked) {
      selectedRadios.push({filterValue : inputs[i].value, latestchoice : selectedRadios.length});
    }
  }

  // sort value by last choice
  selectedRadios.sort(function(a, b) {
        return a.latestchoice - b.latestchoice;
    }),
      
  // parse data 
  var obj = JSON.parse(selectedRadios),

    for (var s = 0;s < obj.length;s++) {
      selectedRadios_latestchoice.push(obj[s].filterValue);
  }

  // return last value of the array "selectedRadios_latestchoice"
  return selectedRadios_latestchoice[selectedRadios_latestchoice.length];
}

The logic is:

My attempt return an error. Any help?

Upvotes: 0

Views: 394

Answers (1)

dale landry
dale landry

Reputation: 8610

There may be a more eligant way to do this, but I was able to use a forEach loop with a nested event listener running a function. In the function we run the event.target through a conditional that checks e.target.checked, if this returns true we push the value into an array, we then reduce that array creating an obj that saves the arr.length as property and the current value as value. Then we push that object into a final array to force the key from auto sorting.

const checkboxes = document.querySelectorAll('.check')

let val = []
const keyValPair = []

checkboxes.forEach((value) => {
  value.addEventListener('change', getPositionAndValue)
})

function getPositionAndValue(e) {
  if (e.target.checked) {
    val.push(e.target.value)
    var result = val.reduce(function(result, curr) {
      result[val.length] = curr;
      return result;
    }, {})
    keyValPair.push(result)

    console.log(keyValPair)
  }
}
<input class="check" value="167" type="checkbox">
<input class="check" value="168" type="checkbox">
<input class="check" value="169" type="checkbox">
<input class="check" value="170" type="checkbox">
<input class="check" value="171" type="checkbox">

Upvotes: 1

Related Questions