Reputation: 15118
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 originally set up a jsFiddle to illustrate my problem: http://jsfiddle.net/GJdBR/
After receiving some advice on answers below I created a new jsfiddle and it worked. http://jsfiddle.net/2UbqP/
However, on my computer I am using a clean install of windows 7, all I have done so far, is install chrome, apanta and xampp. I go to localhost/website and the site comes up, however the js functionality doesn't work, the select box isn't being filled with the var even though I proved the code is correct because of the jsfiddle above.
I am getting an error on this:
$(document).ready(function() {
populateTranslationOptions();
});
The error reads:
Uncaught SyntaxError: Unexpected token ILLEGAL
Upvotes: 1
Views: 2438
Reputation: 87073
$.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()
.
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:
Upvotes: 1
Reputation: 895
For arrays, $.each is unnecessary. You can use a simple loop rather. Like as follows -
function populateTranslationOptions()
{
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();
});
Upvotes: 1
Reputation: 13471
You have several problems in your code. check this
function populateTranslationOptions ()
{
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) {
populateTranslationOptions;
doesnt call the function
populateTranslationOptions();
does.Upvotes: 1