lundi 21 janvier 2019

How to set dropdown select through data-attribute or text?

I am working on a JavaScript function which should copy shipping address form values to a billing address form section in case both are identical.

I wanted to rely either on a data attribute, text or innerHTML to set the select, since option id changes once a selection has been made.

<select id="order_bill_to_land" name="order[bill_to_land_id]"><option value="">select a country</option>
  <option value="1" data-land="1">Afghanistan</option>
  <option value="2" data-land="2">Aland Islands</option>
  <option value="3" data-land="3">Albania</option>

My JavaScript function is:

let land = document.querySelector("#country").getAttribute('data-country');
let bl = document.querySelector("#order_bill_to_land");

for (let i = 0; i < bl.options.length; i++) {
  if (bl.options[i].text === land) {
    return console.log("if loop working");
    bl.selectedIndex = i;
    break;
  };
}

Which produces 0, because the if conditional does not work which I deduce from the fact that I am unable to log to console.

Why is that so?

I found a shorter version for selecting the selectedIndex:

bl.selectedIndex = [...bl.options].findIndex (option => option.innerHTML === land);

but it produces -1. Since it is so nicely condensed I am unable to find out why it does not work.

How can I get this working?

Thank you in advance!

Aucun commentaire:

Enregistrer un commentaire