Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load an external file in JavaScript?

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.

like image 562
Joseph Avatar asked Nov 17 '15 11:11

Joseph


People also ask

What is external file in JavaScript?

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.

How do I write a function in an external JavaScript file?

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.

How do I run a local file in JavaScript?

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.


2 Answers

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);
  });
});
like image 160
Yeldar Kurmangaliyev Avatar answered Oct 09 '22 20:10

Yeldar Kurmangaliyev


You can put the options in a JSON file and load them using AJAX (http) request.

like image 39
Alexander Elgin Avatar answered Oct 09 '22 19:10

Alexander Elgin