0

I would like to know the best approach to use JavaScript to create a new HTML element <option> from each item in an array (or perhaps not use an array if there's a better method?

How would I run a loop that creates a new option for each item in the array and then assign the url as the options value.

Here is my current JS Fiddle.

My JS is as follows:

    var images = [
  "Sports 1",
    "http://lorempixel.com/50/50/sports/1",
  "Sports 2",
    "http://lorempixel.com/50/50/sports/2",
  "Sports 3",
    "http://lorempixel.com/50/50/sports/3",
];

var index, len;
for (index = 0, len = images.length; index < len; index++) {
    var newoption = document.createElement('option');
    newoption.innerHTML = images[index];
    document.getElementById('imagelist').appendChild(newoption);
}

The html should look like this:

<form id="imageform">
  <select id="imagelist" name="imagelist">
    <option value="http://lorempixel.com/50/50/1">Sports 1</option>
    <option value="http://lorempixel.com/50/50/1">Sports 1</option>
    <option value="http://lorempixel.com/50/50/1">Sports 1</option>
  </select>
</form>
0

2 Answers 2

1

use an object to store your key-value pairs.

var images = {
  "Sports 1" :
    "http://lorempixel.com/50/50/sports/1",
  "Sports 2":
    "http://lorempixel.com/50/50/sports/2",
  "Sports 3":
    "http://lorempixel.com/50/50/sports/3",
};

var index, len;
var keys  = Object.keys(images);

for (index = 0, len = keys.length; index < len; index++) {
    var temp = keys[index];
    var newoption = new Option(temp, images[temp]);
    document.getElementById('imagelist').add(newoption);
}

https://jsfiddle.net/Luyxqu75/2/

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

Comments

0

Instead of array, you should have array of objects

Try this:

var images = [{
  "key": "Sports 1",
  "value": "http://lorempixel.com/50/50/sports/1"
}, {
  "key": "Sports 2",
  "value": "http://lorempixel.com/50/50/sports/2"
}];

for (var index = 0, len = images.length; index < len; index++) {
  var newoption = document.createElement('option');
  newoption.value = images[index].value;
  newoption.innerHTML = images[index].key;
  document.getElementById('imagelist').appendChild(newoption);
}
<form id="imageform">
  <select id="imagelist" name="imagelist">
  </select>
</form>

Fiddle

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.