peterHasemann peterHasemann - 4 years ago 113
jQuery Question

Fill Html Selection "FontSize" by JavaScript

I want to fill my Selection by Script. I am struggling with the filling method.

When I want to fill my FontSizeMenu I use this code:

function FillFontSizeMenu() { // run this at Start
FillSelection(GetPossibleFontSizes(), "fontSizeMenu"); // Fill the selection with values
}

function GetPossibleFontSizes(){ // Return all values for the menu
var sizeMin = 1;
var sizeMax = 100;
var possibleSizes = [];
for(var i = sizeMin; i <= sizeMax; i++)
{
possibleSizes.push(i);
}
return possibleSizes;
}


function FillSelection(possibleValues, elementId){ // Fill the menu
for(var i = 0; i < possibleValues.length; i++)
{
var optionElement = "<option></option>"; // add one option element per value
optionElement.html(possibleValues[i]);
optionElement.val(possibleValues[i]);
$(elementId).append(optionElement); // add the option element to the selection
}
}


Something is wrong with the "FillSelection" method, it says the option element is not a function.

Does someone knows what is wrong or missing?

Thanks

Answer Source

Here is one more solution You need to create new Option object

 $(elementId).append(new Option("Font size "+i, possibleValues[i]));

and you should pass #id to function:

FillSelection(GetPossibleFontSizes(), "#fontSizeMenu")

function FillFontSizeMenu() { // run this at Start
  FillSelection(GetPossibleFontSizes(), "#fontSizeMenu"); // Fill the selection with values
}

function GetPossibleFontSizes(){ // Return all values for the menu
  var sizeMin = 1;
  var sizeMax = 100;
  var possibleSizes = [];
  for(var i = sizeMin; i <= sizeMax; i++)
  {
    possibleSizes.push(i);
  }
  return possibleSizes;
}

function FillSelection(possibleValues, elementId){ // Fill the menu
  for(var i = 0; i < possibleValues.length; i++)
  {
    $(elementId).append(new Option("Font size "+i, possibleValues[i])); // add the option element to the selection
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="FillFontSizeMenu()">Populate it</button>
<select id="fontSizeMenu">
</select>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download