Search code examples
javascriptjqueryjquery-selectors

Combining javascript code with different selector IDs correctly


I have about 30 selectors with different IDs example code with which I provided below

document.getElementById("selector-1").onchange = function() {
  document.getElementById("btn-1").href = "/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
}

document.getElementById("selector-2").onchange = function() {
  document.getElementById("btn-2").href = "/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
}

document.getElementById("selector-3").onchange = function() {
  document.getElementById("btn-3").href = "/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
}

Could you please let me know how I can combine all this into something more universal, so as not to bring all the code every time with different IDs, because I see that this is very unoptimized code at the moment. Unfortunately, my knowledge is not enough to refactor this into something more effective. Thanks folks.


Solution

  • Not seeing the HTML (so I could use closest for example) you can try delegation from the nearest static container (here I have to use document, again since I do not see your HTML)

    document.addEventListener("change", function(e) {
      const tgt = e.target;
      if (tgt.id.startsWith("selector-")) {
        const id = tgt.id.replace("selector-", "btn-");
        document.getElementById(id).href = "/?add-to-cart=" + tgt.selectedOptions[0].getAttribute('data-product') + "&variation_id=" + tgt.value + "/";
      }
    })
    

    Alternatively get the value on click:

    document.addEventListener("click", function(e) {
      const tgt = e.target;
      if (tgt.id.startsWith("btn-")) {
        const id = tgt.id.replace("btn-", "selector-");
        const sel = document.getElementById(id);
        tgt.href = "/?add-to-cart=" + sel.selectedOptions[0].getAttribute('data-product') + "&variation_id=" + sel.value + "/";
      }
    })