Mimic Javascript actions on identical element?

I have a PHP plugin that will output some controls that will peform a couple Ajax calls that affect a different element on a page. In this case, it’s to filter some posts containing restaurants in the area. For example, the form will let the user only show restaurants that serve Sushi.

The problem is that I want the controls to actually affect 2 sets of elements.

So, what I’m thinking I can do is use the plugin to add the controller twice, then hide the “second” controller with CSS, then use Javascript to mimic the actions of the first controller onto the second controller (even though it’s hidden to the user).

Does anybody have a Codepen to demonstrate how this would work?

Do you have an example of the HTML you’re trying to manipulate?

1 Like


The checkboxes with the red background will filter the items in the middle column, while the checkboxes with the blue background will filter the map column. The plugin doesn’t support having one control filter both the map and the list.

I mean, there are a few ways to go about it; the simplest to my mind is to hide the red box; then something like…

document.querySelectorAll("[data-content-provider='jet-engine'] input").forEach((x) => {
  x.addEventListener('click', function(e) { document.querySelector(`[data-content-provider='jet-engine-maps'] input[value="${e.target.value}"]`).checked = e.target.checked; });

(I’m spitballing this, as it’s late for me at the moment. Someone do this better than me while i sleep. :stuck_out_tongue: )

Doesn’t seem to work… The code will check the “hidden” box, but it doesn’t actually update the filter.

I’m thinking the filter might update when a box is actually clicked…

So taking m_hutley’s code, expanding it and implementing your click idea.

const toggleCheck = (sourceElem) => {
  const targetElem = document.querySelector(
    `[data-content-provider='jet-engine-maps'] input[value="${sourceElem.value}"]`

  // if no matching target element found then just return
  if (targetElem === null) return

  // if the target checkbox state doesn't match the source checkbox 
  // then fire a click on it
  if (targetElem.checked !== sourceElem.checked) {

const checkBoxes = document.querySelectorAll(
  "[data-content-provider='jet-engine'] input"

checkBoxes.forEach((checkBox) => {
  checkBox.addEventListener('click', (event) => toggleCheck(event.target))

Obviously untested.

Edit: I did do a quick test on your site in the console to fire a click on the second bakery input, and it did appear to work.

document.querySelector('.has-vivid-red-background-color [data-label="Bakery"]').click()
1 Like