Home > Mobile >  Array displays words by each letter than than words. Javascript
Array displays words by each letter than than words. Javascript

Time:10-22

I'm new to JS and I'm trying to populate a dropdown menu with items from an array but every time I loop through the array it displays letter after letter rather than the full string. Please let me know what am I doing wrong. Thank you

JS:

var ProjectNames = [];
ProjectNames = CProject;
var select = document.getElementById("ProjectList");
for (var i = 0; i < ProjectNames.length; i  ) {
    var el = document.createElement("option");
    console.log(ProjectNames[i]);
    var opt = ProjectNames[i];
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);
}

HTML:

<select id="ProjectList" onchange="AddHoursForm()">
<option> --Choose Project-- </option>
</select>

Data in array is coming from Firebase. If I print console.log(ProjectNames) it gives the array objects but if I do console.log(ProjectNames[i]) it prints it letter by letter.

CodePudding user response:

It seems to be working for me. Make sure you are working with an array.

var ProjectNames = [];
ProjectNames = ["hello", "world"];

console.log(ProjectNames)   // <--- check this is this array?

var select = document.getElementById("ProjectList");
for (var i = 0; i < ProjectNames.length; i  ) {
  var el = document.createElement("option");
  console.log(ProjectNames[i]);
  var opt = ProjectNames[i];
  el.textContent = opt;
  el.value = opt;
  select.appendChild(el);
}
<select id="ProjectList" onchange="AddHoursForm()">
  <option> --Choose Project-- </option>
</select>

CodePudding user response:

You killed the contents of ProjectNames setting it equal to CProject.

If you want to add itemns to ProjectNames use push or ProjectNames[ProjectNames.length]=... as below: The rest is ok.

var CProject="four";
var ProjectNames = ["one","two","three"];
ProjectNames[ProjectNames.length]=CProject;
ProjectNames.push("five");

var select = document.getElementById("ProjectList");
for (var i = 0; i < ProjectNames.length; i  ) {
    var el = document.createElement("option");
    console.log(ProjectNames[i]);
    var opt = ProjectNames[i];
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);
}

CodePudding user response:

  • It would be really easy for you if you use template strings or template literals for achieving this.
  • Just get data, create element, append it upon your ease.

// selecting div ith id = "main"
const main = document.querySelector("#main");
// you data from firebase or any other data source
let data = ["option1", "option2"];
// creating an element using tamplate string
const mySelectElement = `
<select>
<option value="" disabled selected>Choose a option</option>
${data.map(option => `<option value="${option}">${option}</option>`).join('')}
</select>
`;
//appeding element
main.innerHTML = mySelectElement;
<div id="main">
</div>

  • Related