1

I have this following html code

<select>
  <option>Joe</option>
  <option>Buckey</option>
  <option>Elen</option>
  <option>Rimzy</option>
</select>
<button>Submit</button>

what I want is, when I click the submit button it should store all the name values which are inside option tags to an array. so far I tried the following js code but it seems not working.

document.getElementsByTagName('button').onclick = function() {
  var array = [document.getElementsByTagName('option').value];
  console.log(array);
};

any idea how can I achieve this? thanks in advance.

ps: I'm quite new to javascript.

2
  • 2
    Is this homework? Commented Feb 16, 2017 at 17:50
  • getElementsByTagName returns a collection of elements...not a single element. You need to iterate that collection to create the array Commented Feb 16, 2017 at 17:51

3 Answers 3

3

Here's the solution. You have to iterate through all option elements, grab the value of every element and push inside an array.

function getValues() {
  var array = document.getElementsByTagName('option');
  var arr = [];
  for (var i = 0; i < array.length; i++) {
    arr.push(array[i].value)
  }
  console.log(arr);
};
<select id="options">
  <option>Joe</option>
  <option>Buckey</option>
  <option>Elen</option>
  <option>Rimzy</option>
</select>
<button id="submit" onclick="getValues()">Submit</button>

ES6 solution:

function getValues() {
  var array = document.getElementsByTagName('option');
  var arr = [];
  Array.from(array).forEach(v => arr.push(v.value));
  console.log(arr);
};
<select id="options">
  <option>Joe</option>
  <option>Buckey</option>
  <option>Elen</option>
  <option>Rimzy</option>
</select>
<button id="submit" onclick="getValues()">Submit</button>

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

1 Comment

Does this answer satisfy you? You can upvote&mark as the best answer if you want :)
2

Assuming that ES6 is an option for you, then the following will do as you wish:

// using a named function:
function grabTextFrom() {

  // initialising the local variable using 'let',
  // converting the argument supplied to Array.from()
  // to convert the Array-like Object (in this case
  // a NodeList, or HTMLCollection, from
  // document.querySelectorAll()) into an Array:
  let texts = Array.from(
    document.querySelectorAll(

      // 'this' is passed automatically from the
      // later use of EventTarget.addEventListener(),
      // and the dataset.textFrom property value is
      // the value stored in the data-textfrom attribute:
      this.dataset.textfrom
    )

  // iterating over that Array of elements using
  // Array.prototype.map() along with an arrow function:
  ).map(

    // 'opt' is a reference to the current Array-element
    // from the Array of elements over which we're iterating;
    // and here we return the value property-value of that
    // current element:
    opt => opt.value
  );

  // logging to the console for demo purposes:
  console.log(texts);

  // returning to the calling context:
  return texts;
}

// finding the first element which matches the
// supplied CSS selector, and adding the
// grabTextFrom() function as the event-handler
// for the 'click' event (note the deliberate
// lack of parentheses in the function-name):
document.querySelector('#submit').addEventListener('click', grabTextFrom);

function grabTextFrom() {
  let texts = Array.from(
    document.querySelectorAll(this.dataset.textfrom)
  ).map(
    opt => opt.value
  );
  console.log(texts);
  return texts;
}

document.querySelector('#submit').addEventListener('click', grabTextFrom);
<select id="options">
  <option>Joe</option>
  <option>Buckey</option>
  <option>Elen</option>
  <option>Rimzy</option>
</select>
<button id="submit" data-textfrom="option">Submit</button>

If, however, you have to provide for ES5 compatibility then the following will work identically:

function grabTextFrom() {

  // here we use Array.prototype.slice(), along
  // with Function.prototype.call(), to apply
  // the slice() method to the supplied NodeList:
  var texts = Array.prototype.slice.call(
    document.querySelectorAll(this.dataset.textfrom)

  // here we use the anonymous function of the
  // Array.prototype.map() method to perform the
  // same function as above, returning the
  // opt.value property-value to the created Array:
  ).map(function(opt) {
    return opt.value;
  });
  console.log(texts);
  return texts;
}

document.querySelector('#submit').addEventListener('click', grabTextFrom);

function grabTextFrom() {
  var texts = Array.prototype.slice.call(
    document.querySelectorAll(this.dataset.textfrom)
  ).map(function(opt) {
    return opt.value;
  });
  console.log(texts);
  return texts;
}

document.querySelector('#submit').addEventListener('click', grabTextFrom);
<select id="options">
  <option>Joe</option>
  <option>Buckey</option>
  <option>Elen</option>
  <option>Rimzy</option>
</select>
<button id="submit" data-textfrom="option">Submit</button>

1 Comment

It is amazing. Great use of Array.from().
0

You're close.

document.getElementsByTagName('option') returns an array of <option> elements.

You can't get .value on an array of elements - you can only call it on a single <option> element.

How would you get .value for each element in your array?

Comments

Your Answer

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