Auto Populate Select Box
I am trying to auto populate a select box using Jquery and JavaScript. I done some searching and came across this question and followed the advice of the selected answer. I origin
Solution 1:
You have several problems in your code. check this
functionpopulateTranslationOptions ()
{
var translationOptions = ["Egyptian Hieroglyphs", "Al Bhed (Final Fantasy X)", "Futurama"];
$.each(translationOptions ,function(i,value) {
$('#translationOptions')
.append($("<option></option>")
.attr("value",value)
.text(value));
});
}
$(document).ready(function() {
populateTranslationOptions();
});
Problems in your code:
$.each syntax is wrong
$.each(translationOptions (value)) {
Should be
$.each(translationOptions ,function(i,value) {
- You were not calling the function
populateTranslationOptions;
doesnt call the functionpopulateTranslationOptions();
does.
Solution 2:
For arrays, $.each is unnecessary. You can use a simple loop rather. Like as follows -
functionpopulateTranslationOptions()
{
var translationOptions = ["Egyptian Hieroglyphs", "Al Bhed (Final Fantasy X)", "Futurama"];
for (var i = 0; i < translationOptions.length; i++) {
$('#translationOptions')
.append('<option value="' + translationOptions[i] + '">' + translationOptions[i] + '</option>');
};
}
$(document).ready(function() {
populateTranslationOptions();
});
Solution 3:
$.each(translationOptions, function (index, value) {
$('#translationOptions')
.append($("<option></option>")
.attr("value",value)
.text(value));
});
You've tried
$.each(translationOptions, (value) )
it's wrong, because correct structure is $.each(mapData, callbackFunction)
, here mapData
means Object or Array.
And next issue is:
$(document).ready(function() {
populateTranslationOptions;
});
It should ne
$(document).ready(function() {
populateTranslationOptions(); // you missed () here
});
Mind that, populateTranslationOptions
doesn't call a function, so to call a function you need to populateTranslationOptions()
.
One important note
The () after a function means to execute the function itself and return it's value. Without it you simply have the function, which can be useful to pass around as a callback.
Related refs:
Post a Comment for "Auto Populate Select Box"