0

I am attempting to create a bit of JavaScript that, on the click of a button, adds a tag filled with options. The options will be defined with an array called "roster". What I would like to see is a dropdown that has options for sanchez, ronaldo, and ozil.

var roster = [
  "ozil",
  "sanchez",
  "ronaldo"
];

var reps = null;
var dropdown = null;
var scorerOption = "<option value='" + reps + "' class='scorerOption'>" + roster[reps] + "</option>";

function makeDropdown () {
  dropdown = "<select class='scorer'>" + String(scorerOption).repeat(roster.length) + "</select>";
  document.getElementById("rawr").innerHTML = dropdown;
}
<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
  <p id="rawr"><button onclick="makeDropdown()">Select a player</button></p>
</body>
</html>

As you may notice, the and tags appear, but all have innerHTML's and values of "undefined". How can I change that so it displays the names sanchez, ronaldo, and ozil?

J. Smith
  • 60
  • 6

1 Answers1

0

You'll need to loop through the array and for each element in the array, create and insert a new option.

You should also not use inline HTML event handling attributes (onclick), see here for why.

Lastly, it's generally better to create dynamic elements with the DOM API call of document.createElement(), rather than build up strings of HTML as the strings can become difficult to manage and the DOM API provides a clean object-oriented way to configure your newly created elements.

var roster = [
  "ozil",
  "sanchez",
  "ronaldo"
];

// Work with your DOM elements in JavaScript, not HTML
var btn = document.getElementById("btn");
btn.addEventListener("click", makeDropdown);

function makeDropdown () {
  // Dynamically generate a new <select> element as an object in memory
  var list = document.createElement("select");
  
  // Configure the CSS class for the element
  list.classList.add("scorer");
  
  // Loop over each of the array elements
  roster.forEach(function(item){
    // Dynamically create and configure an <option> for each
    var opt = document.createElement("option");
    opt.classList.add("scorerOption");
    opt.textContent = item;
    // Add the <option> to the <select>
    list.appendChild(opt);
  });

  // Add the <select> to the document
  document.getElementById("rawr").appendChild(list);
}
<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
  <p id="rawr"><button id="btn">Select a player</button></p>
</body>
</html>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • I appreciate your answer, but I actually figured out the problem on my own. I simply needed to update the page after converting the dropdown to a string. From there, it all worked out. – J. Smith Jul 12 '17 at 19:27
  • @J.Smith Glad it worked out for you, but you should know that your solution is pretty inefficient and doesn't follow best-practices. – Scott Marcus Jul 12 '17 at 21:32