Pablo
Pablo

Reputation: 534

Store into an array selected options from differents selects with javascript

I have a n number of selects like those:

<select id="select1">
        <option value="1">test1</option>
        <option value="2" selected="selected">test2</option>
        <option value="3">test3</option>
    </select>

    <select id="select2">
        <option value="1">asdf</option>
        <option value="2" selected="selected">fdsa</option>
        <option value="3">asdf</option>
    </select>

And I want to select an option in each one, after that click a button and those options are stored into an array so I can format it like a JSON later. I have the following code working for one option:

<button onClick="GetSelectedItem('select1');">Get Selected Item</button>


var arr1 = [];
    function GetSelectedItem(el)
    {
        var e = document.getElementById(el);
        var strSel =e.options[e.selectedIndex].text;

        arr1.push(strSel);
        console.log(arr1);

    }

but I have no idea how to do this for more than 1 select.

Upvotes: 2

Views: 3783

Answers (1)

James
James

Reputation: 1446

This should work for you.

function getSelectedItems() {
  var elements = document.getElementsByClassName('selectVal');

  var results = [];

  for (var i = 0; i < elements.length; i++) {
    var element = elements[i];
    var strSel = element.options[element.selectedIndex].text;
    results.push(strSel);
  }
  console.log(results);
}
<select id="select1" class="selectVal">
  <option value="1">test1</option>
  <option value="2" selected="selected">test2</option>
  <option value="3">test3</option>
</select>

<select id="select2" class="selectVal">
  <option value="1">asdf</option>
  <option value="2" selected="selected">fdsa</option>
  <option value="3">asdf</option>
</select>

<button onClick="getSelectedItems()">Get Selected Item</button>

Upvotes: 3

Related Questions