0

I'm using a MVC pattern implemented using IIFE. I get multiple conditional select boxes from the html and put them in the data model.

When I get a select(s) Node/Element contains also the options.

document.querySelectorAll(DOMStrings.selectDepthLevel)

Are options separate child Nodes or just and array inside the Select Node, meaning:

If I have a reference in my data model to the option can I get/modify attributes of the option without needing to go thru the parent Select Node ?

2
  • 1
    Options are separate elements indeed. Commented Nov 26, 2017 at 9:32
  • 1
    To answer your question: yes. Commented Nov 26, 2017 at 9:35

1 Answer 1

1

Here is a little help :-)

var select = document.getElementById("select");

var data = [{
  value: "option1",
  label: "Option 1"
}, {
  value: "option2",
  label: "Option 2"
}, {
  value: "option3",
  label: "Option 3"
}];

data.forEach(function (x, i) {
  var option = document.createElement("option");
  option.setAttribute("value", data[i].value);
  option.innerHTML = data[i].label;
  select.appendChild(option);
});

function revealData () {
  alert(JSON.stringify(data, 0, 2));
}

function revealHtml () {
  alert(select.innerHTML.replace(/></g, ">\n<"));
}

function editOption (n) {
  var option, value, label, i;
  value = prompt("Value for option #" + n + ":");
  if (value !== null) {
    label = prompt("Label for option #" + n + ":");
    if (label !== null) {
      i = n - 1;
      data[i].value = value;
      data[i].label = label;
      option = select.childNodes[i];
      option.setAttribute("value", data[i].value);
      option.innerHTML = data[i].label;
    }
  }
}
<select id="select"></select>
<button type="button" onclick="editOption(1)">Edit 1</button>
<button type="button" onclick="editOption(2)">Edit 2</button>
<button type="button" onclick="editOption(3)">Edit 3</button>
<button type="button" onclick="revealData()">Reveal data</button>
<button type="button" onclick="revealHtml()">Reveal HTML</button>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.