2

I have a javascript file (country.js) which has some function written like getcountry() and setcountry() etc. getCountry has the list of all the countries. Now I want to use this function to show all countries in a combo-box on my web page. but I do not how to call this function in html section.

this is some part of country.js file.

 ------------------Country.js--------------------------   
function _getCountries() {

}

function _setCountries() {
    _countries.push({ CountryID: 1, Name: 'Germany' });
    _countries.push({ CountryID: 2, Name: 'India' });
    _countries.push({ CountryID: 3, Name: 'China' });
    .................................................
}

I am trying something like that but do not know how to use this function in html part. I am new on web development.

      -------------HTML--------------------------
      <div>
    <select onchange="Country()">
    
    //what to do in this section?
    </select>
   </div>

     ___________ javaScript__________________
    function Country{

           getCountries();
       //what to do in this section?
           }

1 Answer 1

1

_countries is an array which contains all your object.

make _countries to global variable and use in

function _getCountries() {
   return _countries;
}

var myDiv = document.getElementById("myDiv");

//Create array of options to be added
var array = [{ CountryID: 1, Name: 'Germany' },{ CountryID: 2, Name: 'India' },{ CountryID: 3, Name: 'China' }];

//Create and append select list
var selectList = document.createElement("select");
selectList.setAttribute("id", "mySelect");
myDiv.appendChild(selectList);

//Create and append the options
for (var i = 0; i < array.length; i++) {
    var option = document.createElement("option");
    option.setAttribute("value", array[i]);
    option.text = array[i].Name+"-"+array[i].CountryID;
    selectList.appendChild(option);
}
<div id="myDiv">Append here</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.