0

Suppose I have an HTML select object with nothing in it.

<select id="options">
</select>

Is it possible to attach a JavaScript array to this select so that when the array is updated so are the available options in the select?

Or will I just have to use JQuery to achieve what I want.

freedomn-m
  • 27,664
  • 8
  • 35
  • 57
  • You don't *have* to use *jquery*; jquery is just a javascript framework that makes things easier and more succinct (and, historically, more browser compatible). This could be achieved with angular: https://stackoverflow.com/questions/35945001/binding-select-element-to-object-in-angular – freedomn-m Jul 17 '18 at 16:08
  • This is exactly what [Vue.js](https://vuejs.org/) is designed for ;) – BenM Jul 17 '18 at 16:09
  • Thank you all, I wasn't sure if there was a nice way to do it, which clearly there is as you've mentioned :-) –  Jul 17 '18 at 16:09

2 Answers2

1

Any JavaScript framework using a Virtual DOM (Angular, Vue.js, React...) will make this much easier (and faster) than jQuery or Vanilla JavaScript. That said, frameworks can't coexist with each other and are very bad at coexisting with libraries like jQuery; I recommend basing the decision on more than just a problem like this, which can be solved with and without any of them.

Here it is in Vue; the most to-the-point framework I've worked with:

new Vue({
  el: '#options',
  data: {
    array: [
      'option 1',
      'option 2',
      'i lost count'
    ]
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<select id="options">
  <option v-for="value in array">
    {{ value }}
  </option >
</select>
wordbug
  • 641
  • 5
  • 10
0

You can make function and run it every time if your array is updated. jQuery no have any method like arrayChanged. Initialize function manual after array is changed.

function updateSelect(arr) {

    // code with jQuery each or clean JS

}


// code to change array
var arr = ...


// run select updater
updateSelect(arr);
Perfecto Web
  • 182
  • 6