getAttribute is not setting

Asked by At

I need these two drop-down boxes to be synced based on selection of the first box.

I cannot use the "value" tag for this as the codebase pulls in these values from elsewhere.

The following code does not work:

html

<select name="alpha">
  <option id="1" data-sync="1">One</option>
  <option id="2" data-sync="2" selected>Two</option>
  <option id="3" data-sync="3">Three</option>
  <option id="4" data-sync="1">Four One</option>
  <option id="5" data-sync="2">Five Two</option>
</select>
<select name="beta">
  <option value="1" id="1" name="1" syncOne="1">2</option>
  <option value="2" name="2"  id="2" syncOne="2">4</option>
  <option value="3" name="3" id="3" syncOne="3">6</option>
</select>

JavaScript

window.onload = function()
{
    document.getElementsByName("alpha")[0].onchange = function()
    {
        document.getElementsByName("beta")[0].getAttribute("syncOne") = this.options[this.selectedIndex].getAttribute("data-sync"); 
    }

    // Trigger when loading.
    document.getElementsByName("alpha")[0].onchange();
}

However, the next code change works but is out of project spec (I can't use value attribute).

document.getElementsByName("beta")[0].value = this.options[this.selectedIndex].getAttribute("data-sync");

Any suggestions?

1 Answers

4
Shidersz On Best Solutions

First, note that syncOne isn't an attribute of <select name="beta">, instead it is an attribute available on each option related to that selector, so next code will not result on what you are expecting:

document.getElementsByName("beta")[0].getAttribute("syncOne") = ...;

Now, one solution is to use querySelector() to get the related option element from the beta selector, and then set the selected attribute of that option:

Example:

window.onload = function()
{
  document.getElementsByName("alpha")[0].onchange = function()
  {
    let sel = this.options[this.selectedIndex].getAttribute("data-sync");
    let betaOpt = document.querySelector(`select[name="beta"] option[syncOne="${sel}"]`);
    betaOpt.selected = true;
  }

  // Trigger when loading.
  document.getElementsByName("alpha")[0].onchange();
}
<select name="alpha">
  <option id="1" data-sync="1">One</option>
  <option id="2" data-sync="2" selected>Two</option>
  <option id="3" data-sync="3">Three</option>
  <option id="4" data-sync="1">Four One</option>
  <option id="5" data-sync="2">Five Two</option>
</select>
<select name="beta">
  <option value="1" id="1" name="1" syncOne="1">2</option>
  <option value="2" name="2" id="2" syncOne="2">4</option>
  <option value="3" name="3" id="3" syncOne="3">6</option>
</select>

Note, I used a template literal (ES6 feature) to generate the query string of querySelector(). In case you can't use it, you can go with string concatenation, like this:

let betaOpt = document.querySelector('select[name="beta"] option[syncOne="' + sel + '"]');