2

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.

2
  • 1
    Use class instead of ID to bind. Commented Aug 10, 2016 at 8:06
  • Tried using as a parameter the class and that outputs an undefined since it passes the whole list not the selected ones, can you give me an example please? Commented Aug 10, 2016 at 8:15

1 Answer 1

3

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>

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

2 Comments

Now if I want to include also inputs, do I need to create a new function and then join the data? I need to manage inputs and selects only with a single button.
You can use the same function but get inputs and assign to another variables for easier manipulation

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.