Home > Software design >  Any idea how I can change this jQuery into ES6?
Any idea how I can change this jQuery into ES6?

Time:10-13

I have this block of code

$( ".asset-type-select" ).change(function() {
  var selectedEventType = this.options[this.selectedIndex].value;
  if (selectedEventType == "all") {
    $('.asset-type div').removeClass('hidden');
  } else {
    $('.asset-type div').addClass('hidden');
    $('.asset-type div[data-eventtype="'   selectedEventType   '"]').removeClass('hidden');
  }
});

and it needs to be vanilla JS/ES6 as jQuery no longer exists on the system... Any ideas how I can revert it

I've got it this far, but it's not working :/

const assetChoose = document.getElementById('asset-type-select');
const filterBy = document.querySelectorAll('.asset-type div');
assetChoose.addEventListener('change', () => {
  const selectedAssetType = assetChoose.options[assetChoose.selectedIndex].value;
  if (selectedAssetType === 'all') {
    for (let i = 0; i < filterBy.length; i  ) { // eslint-disable-line no-plusplus
      filterBy[i].classList.remove('hidden');
    }
  } else {
    for (let j = 0; j < filterBy.length; j  ) { // eslint-disable-line no-plusplus
      filterBy[j].classList.add('hidden');
    }
    const hiddenDiv = document.querySelectorAll(`.asset-type div[data-assettype="${selectedAssetType}"]`);
    for (let k = 0; k < hiddenDiv.length; k  ) { // eslint-disable-line no-plusplus
      hiddenDiv[k].classList.remove('hidden');
    }
  }
});

<select id="asset-type-select">
  <option value="all" selected="selected">All</option>
  <option value="Science">Science</option>
  ...
</select>

<div class="asset-type">
  <div data-assettype="Science">
    ...
  </div>
  <div>...</div>

Frankly, I think this could be better, but I'm at a loss... I'd like to get rid of the i type references as well.

The code seems to run but doesn't throw any errors, but also doesn't do what it's intended to do either...

Any ideas would be greatly appreciated.

CodePudding user response:

this code works for me

<select id="asset-type-select">
 <option value="all" selected="selected">All</option>
 <option value="Science">Science</option>
 ...
</select>

<div class="asset-type">
  <div data-assettype="Science">...</div>
  <div>...</div>
</div>

<script>
  const assetChoose = document.getElementById("asset-type-select");
  const filterBy = document.querySelectorAll(".asset-type div");
  assetChoose.addEventListener("change", () => {
    const selectedAssetType =
      assetChoose.options[assetChoose.selectedIndex].value;
    if (selectedAssetType === "all") {
      filterBy.forEach((div) => div.classList.remove("hidden"));
    } else {
      filterBy.forEach((div) => div.classList.add("hidden"));
      const hiddenDiv = document.querySelectorAll(
        `.asset-type div[data-assettype="${selectedAssetType}"]`
      );
      hiddenDiv.forEach((div) => div.classList.remove("hidden"));
    }
  });
</script>
  • Related