Reputation: 387
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?
}
Upvotes: 2
Views: 136
Reputation: 1727
_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>
Upvotes: 1