I am writing a script where you can add and remove a drop-down list of languages. I got it working but my question is if there is a way to externalize the select tag part of the code as I would have more than 100 options and load it in JavaScript when a link is click. I don't want to have 100 option tags within the script. On the PHP side I use the the include statement to load my list of options.
This is where my problem is.
$(function() {
var scntDiv = $('#container');
var i = $('#container p').size() + 1;
$('#addScnt').live('click', function() {
$('<p><select>I DONT WANT TO HAVE 100 OPTION TAGS HERE</select></p>').appendTo(scntDiv);
i++;
return false;
});
});
here is my code that runs with a few option tags in the script.
Full code.
External JavaScript is when the JavaScript Code(script) is written in another file having an extension . js and then we link this file inside the <head> or<body> tag of our HTML file in which the code is to be added.
Create external JavaScript file with the extension . js. After creating, add it to the HTML file in the script tag. The src attribute is used to include that external JavaScript file.
If you save your JavaScript in it's own file, you can run the entire file at once with nodejs by typing node <filename> where filename is the file you want to run. If you have node installed and you are using a text editor to write JavaScript in separate files you can use your editor to run your code.
You can store your languages as objects. It can be either a static file or dynamically generated response. Then, you can use it for dynamical options creation:
MyLanguages.json:
[
{
'Name': 'English',
'Sign': 'EN'
},
{
'Name': 'Spanish',
'Sign': 'ES'
},
{
'Name': 'Russian',
'Sign': 'RU'
}
]
Your page:
$.ajax({
url: './MyLanguages.json',
dataType: 'json'
}).done(function(data) {
var $select = $("select");
$(data).each(function() {
$("<option/>").text(this.Name).val(this.Sign).appendTo($select);
});
});
You can put the options in a JSON file and load them using AJAX (http) request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With