Reputation: 863
javascript object named countries. Now this data i want to populate in HTML select
var countries = {
India:"delhi",
US:"Norway",
UK:"London",
id: 123752,
allcountries : function(){return this.India +" "+ this.US + " " + this.UK + " "+this.id}
};
HTML Code
<select id="con">
<option></option>
</select>
I tried
document.getElementById("con").innerHTML = countries.allcountries();
$('#con option').append(countries.India);
but it is not working can anyone help me to populate data using jquery/javascript in html select.
Upvotes: 1
Views: 3796
Reputation: 74738
What my suggestion is to have a blank <select>
like this:
<select id="con"></select>
and update your function like this:
var countries = {
India: "delhi",
US: "Norway",
UK: "London",
id: 123752,
allcountries: function () {
return this.India + " " + this.US + " " + this.UK + " " + this.id
},
conToPopulate: function () { // make a new func to return an object
var o = {}; // create an object
o['India'] = this.India; // push the required keys and values
o['US'] = this.US;
o['UK'] = this.UK;
return o; // now outputs : {India: "delhi", US: "Norway", UK: "London"}
}
};
$(function () {
$.each(countries.conToPopulate(), function (key, value) {
$('#con').append($('<option/>', {
value: value,
text: key
}));
});
});
Upvotes: 1
Reputation: 142
In native javascript, you may try the code below:
<script>
var countries = {
India:"delhi",
US:"Norway",
UK:"London"
};
window.onload=function(){
console.log(countries);
var select = document.getElementById("con");
var option;
for (var key in countries) {
option = document.createElement("option");
option.value = key;
option.textContent = countries[key];
select.appendChild(option);
}
};
</script>
<select id="con">
<option></option>
</select>
Upvotes: 1
Reputation: 25882
This worked for me.
HTML:-
<select id="con">
<option></option>
</select>
Javascript:-
var countries = {
India:"delhi",
US:"Norway",
UK:"London",
id: 123752
};
$.each(countries, function (key, value) {
$('#con').append($('<option/>', {
value: value,
text : key
}));
});
It will add capitals of Countries as values of options.
Upvotes: 1
Reputation: 67207
Try,
var countries = {
India: "delhi",
US: "Norway",
UK: "London"
};
$('#con').html($.map(countries, function (val, key) {
return '<option value="' + key + '">' + val + '</option>';
}).join(''));
Upvotes: 2