Fill data in options in select box using jquery - javascript

I have an json array with some data i want to fill all its value in select box option value ...
Array like
[
{
"CityId": "42231",
"CountryID": "1",
"RegionID": "833",
"City": "Herat",
"Latitude": "34.333",
"Longitude": "62.2",
"TimeZone": "+04:30",
"DmaId": "0",
"Code": "HERA"
},
{
"CityId": "5976",
"CountryID": "1",
"RegionID": "835",
"City": "Kabul",
"Latitude": "34.517",
"Longitude": "69.183",
"TimeZone": "+04:50",
"DmaId": "0",
"Code": "KABU"
},
{
"CityId": "42230",
"CountryID": "1",
"RegionID": "852",
"City": "Mazar-e Sharif",
"Latitude": "36.7",
"Longitude": "67.1",
"TimeZone": "+4:30",
"DmaId": "0",
"Code": "MSHA"
}
]
and i want to fill this value in select box using jquery, how can i do this...
i have tried
$.each(json, function(i, value) {
$('#cityselect').append($('<option>').text(value.CityId).attr('value.city', value.City));
});
can anyone help me for this

var data = [{"CityId":"42231","CountryID":"1","RegionID":"833","City":"Herat","Latitude":"34.333","Longitude":"62.2","TimeZone":"+04:30","DmaId":"0","Code":"HERA"},{"CityId":"5976","CountryID":"1","RegionID":"835","City":"Kabul","Latitude":"34.517","Longitude":"69.183","TimeZone":"+04:50","DmaId":"0","Code":"KABU"},{"CityId":"42230","CountryID":"1","RegionID":"852","City":"Mazar-e Sharif","Latitude":"36.7","Longitude":"67.1","TimeZone":"+4:30","DmaId":"0","Code":"MSHA"}];
Now for populating the options:
var $select = $('#cityselect');
$.each(data, function(i , value) {
var option = $('<option value="'+ value.CityId+'">'+ value.City +'</option>');
$select.append(option);
});
Even more better in terms of performance:
var data = [{"CityId":"42231","CountryID":"1","RegionID":"833","City":"Herat","Latitude":"34.333","Longitude":"62.2","TimeZone":"+04:30","DmaId":"0","Code":"HERA"},{"CityId":"5976","CountryID":"1","RegionID":"835","City":"Kabul","Latitude":"34.517","Longitude":"69.183","TimeZone":"+04:50","DmaId":"0","Code":"KABU"},{"CityId":"42230","CountryID":"1","RegionID":"852","City":"Mazar-e Sharif","Latitude":"36.7","Longitude":"67.1","TimeZone":"+4:30","DmaId":"0","Code":"MSHA"}];
var $select = $('#cityselect');
options = [];
$.each(data, function(i , value) {
options.push('<option value="'+ value.CityId+'">'+ value.City +'</option>');
});
$select.html(options.join(""));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="cityselect"></select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<select id="cityselect"></select>
</body>
<script>
$(document).ready(function () {
var listVal=[{"CityId":"42231","CountryID":"1","RegionID":"833","City":"Herat","Latitude":"34.333","Longitude":"62.2","TimeZone":"+04:30","DmaId":"0","Code":"HERA"},{"CityId":"5976","CountryID":"1","RegionID":"835","City":"Kabul","Latitude":"34.517","Longitude":"69.183","TimeZone":"+04:50","DmaId":"0","Code":"KABU"},{"CityId":"42230","CountryID":"1","RegionID":"852","City":"Mazar-e Sharif","Latitude":"36.7","Longitude":"67.1","TimeZone":"+4:30","DmaId":"0","Code":"MSHA"}] ;
$.each(listVal, function(i, value) {
$('#cityselect').append('<option value="'+ value.CityId+'">'+ value.City +'</option>');
});
});
</script>
</html>

You can make use of .val(id) to set the id and .text(name) to set the name of option.
$('#cityselect').append($('<option />').val(value.CityId).text(value.City));
var json = [{"CityId":"42231","CountryID":"1","RegionID":"833","City":"Herat","Latitude":"34.333","Longitude":"62.2","TimeZone":"+04:30","DmaId":"0","Code":"HERA"},{"CityId":"5976","CountryID":"1","RegionID":"835","City":"Kabul","Latitude":"34.517","Longitude":"69.183","TimeZone":"+04:50","DmaId":"0","Code":"KABU"},{"CityId":"42230","CountryID":"1","RegionID":"852","City":"Mazar-e Sharif","Latitude":"36.7","Longitude":"67.1","TimeZone":"+4:30","DmaId":"0","Code":"MSHA"}];
$.each(json, function(i, value) {
$('#cityselect').append($('<option />').val(value.CityId).text(value.City));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='cityselect'> </select>

Related

JSON dependent dynamic dropdown third level array error

I have three dropdowns which are depend on each other. Based on the selection of Dropdown A will have a list of results in Dropdown B, and based on the selection of Dropdown B will have a list of results in Dropdown C.
I can populate the first two dropdowns without a problem. However the last dropdown does shows me incorrect options.
$(function() {
var platforms;
var tasktypes;
var compos;
var jsonData;
$('#addnew').click(function(){
$('#dataset').clone().appendTo($('#newfield'));
});
$.getJSON('tasks.json', function(result) {
jsonData = result;
$.each(result, function(i, platform) {
platforms += "<option value='" +
platform.name +
"'>" +
platform.name +
"</option>";
});
$('#platform').html(platforms);
});
$("#platform").change(function (){
var idx = $("#platform").prop('selectedIndex');
var platforms = jsonData[idx].task;
tasktypes = "";
for (i = 0; i < platforms.length; i++) {
tasktypes += "<option value='" +
platforms[i].taskname +
"'>" +
platforms[i].taskname +
"</option>";
};
$('#taskname').html(tasktypes);
});
$("#taskname").change(function (){
var idc = $("#taskname").prop('selectedIndex');
var tasktypes = jsonData[idc].task[0].component;
compos = "";
for (i = 0; i < tasktypes.length; i++) {
compos += "<option value='" +
tasktypes[i].componentname +
"'>" +
tasktypes[i].componentname +
"</option>";
};
$('#components').html(compos);
});
});
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<button id="addnew">Add new</button>
<div id="dataset">
Platform:
<select id="platform">
</select>
Task Type:
<select id="taskname">
</select>
Component:
<select id="components">
</select>
Units:
<input type="number" min="0" />
</div>
<div id="newfield"></div>
<button id="calculate">Calculate</button>
<button id="clear">Clear</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
Json
[
{
"name": "Sitecore",
"value": "sitecore",
"task": [
{
"taskname": "promobox",
"component": [
{
"componentname": "A",
"time": "20"
},
{
"componentname": "B",
"time": "10"
}
]
},
{
"taskname": "video",
"component": [
{
"componentname": "C",
"time": "20"
},
{
"componentname": "D",
"time": "10"
}
]
}
]
},
{
"name": "Siab",
"value": "siab",
"task": [
{
"taskname": "promobox",
"component": [
{
"componentname": "E",
"time": "20"
},
{
"componentname": "F",
"time": "10"
}
]
},
{
"taskname": "newswire",
"component": [
{
"componentname": "G",
"time": "20"
},
{
"componentname": "H",
"time": "10"
}
]
},
{
"taskname": "video",
"component": [
{
"componentname": "I",
"time": "20"
},
{
"componentname": "J",
"time": "10"
}
]
}
]
}
]
First two dropdowns works fine. Once I select a platform from the first dropdown, second dropdown populates with the relevant tasknames. But once I select a taskname from the second dropdown, third dropdown does show irrelevant data. I can't figure out what's wrong I'm doing here.
I believe the major problem you have is jsonData = result during the ajax request. All ajax requests are asynchronous by default, hence, every data produced from it is mostly non-existent after the request completion. So your best bet will be to pass result to the HTML DOM object during the request.
$.getJSON('tasks.json', function(result) {
$('#platform').data('jsonData',result);//Assign Json data to data object of platform id
$.each(result, function(i, platform) {
platforms += "<option value='" +
platform.name +
"'>" +
platform.name +
"</option>";
});
$('#platform').html(platforms);
});

Dynamic populate dropdown doesn't work

I'm trying to fill a dropdown list dynamically but it doesn't work. here is the code:
<form id="email-compose" class="form-email-compose" method="get" action="">
<div class="form-group">
<select id="input-to" class="input-transparent form-control">
</select>
</div>
<div class="form-group">
<input type="text" id="input-subject" placeholder="Subject" class="input-transparent form-control"
value="<%= subject %>">
</div>
<div class="form-group">
<textarea rows="10" class="form-control" id="wysiwyg" placeholder="Message"><%- body %></textarea>
</div>
<div class="clearfix">
<div class="btn-toolbar pull-xs-right">
<button type="reset" id="compose-discard-button" class="btn btn-gray">Annuler</button>
<button type="submit" id="compose-send-button" onClick="sendMail()" class="btn btn-danger"> Envoyer </button>
</div>
</div>
</form>
and the corresponding JS:
var jsonData = {
"Table": [{
"stateid": "2",
"statename": "Texas"
}, {
"stateid": "3",
"statename": "Louisiana"
}, {
"stateid": "4",
"statename": "California"
}, {
"stateid": "5",
"statename": "Nevada"
}, {
"stateid": "6",
"statename": "Massachusetts"
}]
};
$(document).ready(function () {
var listItems = '<option selected="selected" value="0">- Select -</option>';
for (var i = 0; i < jsonData.Table.length; i++) {
listItems += "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
}
console.log(listItems);
$("#input-to").html(listItems);
});
If I insert manually the option tags, I can see them correctly in the select but not dynamically...
I also tried with .append method but still having an empty drop down list.
Any idea ?
EDIT 1:
I also tried to use .append like this:
$(document).ready(function () {
$('#input-to').append('<option selected="selected" value="0">- Select -</option>');
for (var i = 0,opt; opt= jsonData.Table[i]; ++i) {
$('#input-to').append('<option value="' + opt.stateid + '">' + opt.statename + '</option>');
}
});
but same thing, my dropdown remains empty...
No problem of syntax as if I add manually the options I can see the options available.
one additional thing, my form is surrounded by a script:
<script type="text/template" id="compose-view-template">
....<form>
</script>
with the following js
var ComposeView = Backbone.View.extend({
template: _.template($('#compose-view-template').html()),
attributes: {
id: 'compose-view',
class: 'compose-view'
},
events: {
"click #compose-save-button, #compose-send-button, #compose-discard-button": 'backToFolders'
},
render: function() {
$('#widget-email-header').html(
'<h5>Nouvel <span class="fw-semi-bold">Email</span></h5>'
);
$('#folder-stats').addClass('hide');
$('#back-btn').removeClass('hide');
this.$el.html(this.template(this.model.toJSON()));
this._initViewComponents();
return this;
},
backToFolders: function(){
App.showEmailsView();
},
_initViewComponents: function(){
this.$("textarea").wysihtml5({
html: true,
customTemplates: bs3Wysihtml5Templates,
stylesheets: []
});
}
});
may be the js function is called when the form is not completely created ? hence, there is no action (and no error) because the form is not completely created ?
Your making a small mistake in your code
See the commeted out code below:
var jsonData = {
"Table": [{
"stateid": "2",
"statename": "Texas"
}, {
"stateid": "3",
"statename": "Louisiana"
}, {
"stateid": "4",
"statename": "California"
}, {
"stateid": "5",
"statename": "Nevada"
}, {
"stateid": "6",
"statename": "Massachusetts"
}]
};
$(document).ready(function () {
//
// Since your are adding the html to the element
// You dont need to recreate it!
//
// var listItems = '<option selected="selected" value="0">- Select -
// </option>';
var listItems="";
for (var i = 0; i < jsonData.Table.length; i++) {
listItems += "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
}
console.log(listItems);
$("#input-to").html(listItems);
});
Here is a fiddle of a working version
https://jsfiddle.net/40zz77ex/
Use .append instead of building HTML string. Something like this.
$(document).ready(function () {
$('#input-to').append('<option selected="selected" value="0">- Select -</option>');
for (var i = 0,opt; opt= jsonData.Table[i]; ++i) {
$('#input-to').append('<option value="' + opt.stateid + '">' + opt.statename + '</option>');
}
});
See working example
var jsonData = {
"Table": [{
"stateid": "2",
"statename": "Texas"
}, {
"stateid": "3",
"statename": "Louisiana"
}, {
"stateid": "4",
"statename": "California"
}, {
"stateid": "5",
"statename": "Nevada"
}, {
"stateid": "6",
"statename": "Massachusetts"
}]
};
$(document).ready(function() {
$('#input-to').append('<option selected="selected" value="0">- Select -</option>');
for (var i = 0, opt; opt = jsonData.Table[i]; ++i) {
$('#input-to').append('<option value="' + opt.stateid + '">' + opt.statename + '</option>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="input-to"></select>

Populate select elements dynamically from json data file using jquery

I'am trying to create search box for state districts and villages , but I'am enable to fetch data into combobox.
I have tried so many other way to get data into select boxes they doesn't work. Below is the code I've so far:
HTML:
<div class="dummy__item">
<select name="state_id" id="state_id" tabindex="1">
<option value="">-- Select state --</option>
</select>
</div>
<div class="dummy__item">
<select name="district_id" id="district_id" tabindex="2">
<option value="">-- Select district --</option>
</select>
</div>
<div class="dummy__item">
<select name="village_id" id="village_id" tabindex="3">
<option value="">-- Select village --</option>
</select>
</div>
JS:
<!-- language: lang-js -->
function loadlist(selobj, url) {
$(selobj).empty();
$(selobj).append('<option value="0">--Select Category--</option>')
$(selobj).append(
$.map(jsonList, function(el, i) {
return $('<option>').val(el.slno).text(el.state)
}));
}
loadlist($('select#state_id').get(0), jsonList);
You can do the following (Check the revision history for a shorter version which made use of underscorejs):
The comments should help you get an idea. check https://api.jquery.com/ for detailed information regarding the jQuery methods used.
$(function() {
insert($('#state_id'), plucker(records, 'state'));
//------------------------^ grabs unique states
//--^ populate state list on DOM ready
$('select').on('change', function() {
var category = this.id.split('_id')[0];
var value = $(this).find('option:selected').text();
switch (category) {
case 'state':
{
insert($('#district_id'), plucker(filter(records, 'state', value),'district'));
//-^ insert plucked results to DOM
//------------------------^ plucks districts from filter results
//--------------------------------^ filters districts belonging to selected state
break;
}
case 'district':
{
insert($('#village_id'), plucker(filter(records, 'district', value),'village'));
break;
}
}
});
function plucker(arr, prop) {
// grabs unique items from the required property such as state, district etc from the results
return $.map(arr, function(item) {
return item[prop]
}).filter(function(item, i, arr) {
return arr.indexOf(item) == i;
});
}
function filter(arr, key, value) {
// filters the records matching users selection
return $.grep(arr, function(item) {
return item[key] == value;
});
}
function insert(elm, arr) { // inserts the results into DOM
elm.find('option:gt(0)').remove();
$.each(arr, function(i,item) {
elm.append($('<option>', {
value: i,
text: item
}));
});
}
});
var records = [{
"slno": "1",
"state": "Maharashtra",
"constituency": "Parbhani",
"mp": "Shri Sanjay Haribhau Jadhav",
"district": "Parbhani",
"block": "Jintur",
"village": "Kehal",
"latitude": "77.7",
"longitude": "19.33"
}, {
"slno": "2",
"state": "Maharashtra",
"constituency": "Shirur",
"mp": "Shri Shivaji Adhalrao Patil",
"district": "Pune",
"block": "Shirur",
"village": "Karandi",
"latitude": "77.7",
"longitude": "19.33"
}, {
"slno": "3",
"state": "Maharashtra",
"constituency": "Amravati",
"mp": "Shri Anandrao Vithoba Adsul",
"district": "Amravati",
"block": "Amravati",
"village": "Yavli Shahid",
"latitude": "77.7",
"longitude": "19.33"
}]
$(function() {
insert($('#state_id'), plucker(records, 'state'));
//------^ populate states list on DOM ready
$('select').on('change', function() {
var category = this.id.split('_id')[0];
var value = $(this).find('option:selected').text();
switch (category) {
case 'state':
{
insert($('#district_id'), plucker(filter(records, 'state', value), 'district'));
break;
}
case 'district':
{
insert($('#village_id'), plucker(filter(records, 'district', value), 'village'));
break;
}
}
});
function plucker(arr, prop) {
// grabs unique items from the required property such as state, district etc from the results
return $.map(arr, function(item) {
return item[prop]
}).filter(function(item, i, arr) {
return arr.indexOf(item) == i;
});
}
function filter(arr, key, value) {
// filters the records matching users selection
return $.grep(arr, function(item, i) {
return item[key] === value;
});
}
function insert(elm, arr) {
// inserts the results into DOM
elm.find('option:gt(0)').remove();
$.each(arr, function(i, item) {
elm.append($('<option>', {
value: i,
text: item
}));
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dummy__item">
<select name="state_id" id="state_id" tabindex="1">
<option value="">-- Select state --</option>
</select>
</div>
<div class="dummy__item">
<select name="district_id" id="district_id" tabindex="2">
<option value="">-- Select district --</option>
</select>
</div>
<div class="dummy__item">
<select name="village_id" id="village_id" tabindex="3">
<option value="">-- Select village --</option>
</select>
</div>
In your above code you have made the following mistake,
1.Extra close bracket
$.map(jsonList, function (el, i) {
return $('<option>').val(el.slno).text(el.state)
}));
Update it as
$.map(jsonList, function (el, i) {
return $('<option>').val(el.slno).text(el.state)
});
The looping of json object
$.map(jsonList.listval, function (el, i) {
$('#state_id').append('<option value="'+el.slno+'" attState="'+el.state+'">'+el.state+'</option>');
});
To avoid multiple times the same state repetition, before inserting the option you need to check if the entry is already exist in option if not exist then add it to the select, for this I have introduced a new option attribute "attState". Please look in to the code you will understand what I have done..
$.map(jsonList.listval, function (el, i) {
if ($("#yourSelect option[attState='" + el.state + "']").length == 0) {
$('#yourSelect').append('<option value="' + el.slno + '" attState="' + el.state + '">' + el.state + '</option>');
}
});
For reference refer
Try:
function createOptiolist(list, name) {
var state = list.map(function(obj) {
return obj[name];
});
return state = state.filter(function(v, i) {
return state.indexOf(v) == i;
});
}
var state = createOptiolist(jsonList.listval, "state");
$.each(state, function(i, el) {
$('#state_id').append('<option value="' + el + '">' + el + '</option>');
});
$('#state_id').on('change', function() {
var state = $(this).find('option:selected').val();
$('#district_id').empty();
$.each(jsonList.listval, function(i, el) {
if (el.state == state) {
$('#district_id').append('<option value="' + el.district + '">' + el.district + '</option>');
}
})
});
$('#district_id').on('change', function() {
var district = $(this).find('option:selected').val();
$('#village_id').empty();
$.each(jsonList.listval, function(i, el) {
if (el.district == district) {
$('#village_id').append('<option value="' + el.slno + '">' + el.village + '</option>');
}
})
});
DEMO
DEMO with ajax
Try this plz
HTML
<div class="dummy__item">
<select name="state_id" id="state_id" tabindex="1">
<option value="">-- Select state --</option>
</select>
</div>
<div class="dummy__item">
<select name="district_id" id="district_id" tabindex="2">
<option value="">-- Select district --</option>
</select>
</div>
<div class="dummy__item">
<select name="village_id" id="village_id" tabindex="3">
<option value="">-- Select village --</option>
</select>
</div>
JQUERY
$(document).ready(function(){
// JSON list
var jsonList = {"listval" : [
{
"slno": "1",
"state": "Maharashtra",
"constituency": "Parbhani",
"mp": "Shri Sanjay Haribhau Jadhav",
"district": "Parbhani",
"block": "Jintur",
"village": "Kehal",
"latitude": "77.7",
"longitude": "19.33"
},
{
"slno": "2",
"state": "Maharashtra",
"constituency": "Shirur",
"mp": "Shri Shivaji Adhalrao Patil",
"district": "Pune",
"block": "Shirur",
"village": "Karandi",
"latitude": "77.7",
"longitude": "19.33"
},
{
"slno": "3",
"state": "TEXAS",
"constituency": "XYZ",
"mp": "Shri ABC",
"district": "dist1",
"block": "block1",
"village": "Yavli Shahid",
"latitude": "77.7",
"longitude": "19.33"
},
{
"slno": "4",
"state": "Maharashtra",
"constituency": "Amravati",
"mp": "Shri Anandrao Vithoba Adsul",
"district": "Amravati",
"block": "Amravati",
"village": "Yavli Shahid",
"latitude": "77.7",
"longitude": "19.33"
}]}
// JSON LIST
function loadlist(selobj, url) {
var categories = [];
$(selobj).empty();
$(selobj).append('<option value="0">--Select Category--</option>')
$(selobj).append(
$.map(jsonList.listval, function (el, i) {
if ($.inArray(el.state, categories)==-1) {
categories.push(el.state);
return $('<option>').val(el.slno).text(el.state);
console.log($(el.state));}
}));
}
loadlist($('#state_id').get(0), jsonList);
});

Combo Select using json

The country and state will be sent as json
{
"data": [
{
"country": "USA",
"states": [
"Alabama",
"Alaska",
"Arizona"
]
},
{
"country": "India",
"states": [
"TN",
"AP",
"Mumbai"
]
}
]
}
There will be two select tags (country and state). How do I populate the states based on the country selected?
I am looking for a solution similar to http://www.datatables.net/examples/api/row_details.html where the row.data() returns the data set of a particular row.
Here's a very simple pure JavaScript way to populate two select boxes via JSON. In this example, State is dependent upon which Country is selected.
Example: http://jsfiddle.net/wasfd592/
HTML:
<select id="country">
<option>Country</option>
</select>
<select id="state">
<option>State</option>
</select>
JSON Object (assigned to variable d):
var d = {
"data": [
{
"country": "USA",
"states": [
"Alabama",
"Alaska",
"Arizona"
]
},
{
"country": "India",
"states": [
"TN",
"AP",
"Mumbai"
]
}
]
}
JavaScript:
// First - populate the Country select box from the JSON
for (var i in d.data) {
var elem = document.createElement("option");
elem.value = d.data[i].country;
elem.innerHTML = d.data[i].country;
document.getElementById("country").appendChild(elem);
}
// Next - add an event handler that will trigger when Country is changed and populate the State box
document.getElementById("country").addEventListener("change", function () {
document.getElementById("state").innerHTML = "";
var country = document.getElementById("country").options[document.getElementById("country").selectedIndex].value;
if (country === "Country") {
var elem = document.createElement("option");
elem.value = "State";
elem.innerHTML = "State";
document.getElementById("state").appendChild(elem);
}
for (var i in d.data) {
if (d.data[i].country === country) {
for (var a = 0; a < d.data[i].states.length; a++) {
var elem = document.createElement("option");
elem.value = d.data[i].states[a];
elem.innerHTML = d.data[i].states[a];
document.getElementById("state").appendChild(elem);
}
}
}
});
Try this out:- http://jsfiddle.net/ox4ykqoL/
HTML:-
<select id="country"></select>
<select id="states"></select>
JS:-
jQuery(function ($) {
var input = {
"data": [{
"country": "USA",
"states": [
"Alabama",
"Alaska",
"Arizona"]
}, {
"country": "India",
"states": [
"TN",
"AP",
"Mumbai"]
}]
};
$.each(input.data, function (index, d) {
$("#country").append("<option value=\"" + d.country + "\">" + d.country + "</option>");
});
$("#country").on("change", function () {
var selectedCountry = $("#country").val();
var t = $.map(input.data, function (obj) {
if (obj.country === selectedCountry) return obj;
});
if (t.length != 0) {
$('#states').empty();
debugger;
$.each(t[0].states, function (index, d) {
$("#states").append("<option value=\"" + d + "\">" + d + "</option>");
});
}
});
$("#country").change();
});

Dynamic Knockout table from JSON object

I was trying to populate a table with knockout integration. That takes data from Json.
JSON DATA
{
"info":[
{
"Name":"Noob Here",
"Major":"Language",
"Sex":"Male",
"English":"15",
"Japanese":"5",
"Calculus":"0",
"Geometry":"20"
},
{
"Name":"Noob Here",
"Major":"Calculus",
"Sex":"Female",
"English":"0.5",
"Japanese":"40",
"Calculus":"20",
"Geometry":"05"
}
]
}
I used knockout-mapping to dynamically map the data into the page. That has been added as Javascript in JS-bin. My script is in the sample's html page
$(document).ready(function () {
$("#div1").append("<tr><td data-bind='text: name'></td><td data-bind='text: major'></td><td data-bind='text: sex'></td><td><input data-bind='value: English' /></td><td><input data-bind='value: Japanese' /></td><td><input data-bind='value: Calculus' /></td><td><input data-bind='value: Geometry' /></td></tr>");
function loadData(fileName) {
var data = {
"info": [{
"Name": "Noob Here",
"Major": "Language",
"Sex": "Male",
"English": "15",
"Japanese": "5",
"Calculus": "0",
"Geometry": "20"
}, {
"Name": "Noob Here",
"Major": "Calculus",
"Sex": "Female",
"English": "0.5",
"Japanese": "40",
"Calculus": "20",
"Geometry": "05"
}]
}
return (data);
}
var dataFunction = function () {
this.Items = ko.observableArray([]);
};
var myFile = "Data";
var data = [];
var data1 = {
"info": [{
"Name": "Noob Here",
"Major": "Language",
"Sex": "Male",
"English": "15",
"Japanese": "5",
"Calculus": "0",
"Geometry": "20"
}, {
"Name": "Noob Here",
"Major": "Calculus",
"Sex": "Female",
"English": "0.5",
"Japanese": "40",
"Calculus": "20",
"Geometry": "05"
}]
}
if (data1 && data1.info) {
console.log(data1.info[0]);
$.each(data1.info[0], function (key, value) {
});
$.each(data1.info, function (index, element) {
data.push({
English: element.English,
Japanese: element.Japanese,
Calculus: element.Calculus,
Geometry: element.Geometry,
name: element.Name,
major: element.Major,
sex: element.Sex
});
});
dataFunction.prototype = function () {
var getAllItems = function () {
var self = this;
ko.mapping.fromJS(data, {}, self.Items);
};
var finalObj = {};
var info = [];
$.each(data1.info, function (i, v) {
var object = {};
$.each(v, function (i1, val1) {
if ($.isNumeric(val1)) {
object[i1] = val1
}
});
info.push(object);
});
finalObj['info'] = info;
console.log(finalObj);
return {
getAllItems: getAllItems
}
}();
var dataList = new dataFunction();
dataList.getAllItems();
ko.applyBindings(dataList);
}
});
I want to replace
data.push({
English: element.English,
Japanese: element.Japanese,
Calculus: element.Calculus,
Geometry: element.Geometry,
name: element.Name,
major: element.Major,
sex: element.Sex
});
Into a dynamic script so that what ever json data i add will be shown in the table format. Even if its column name or column number changes.
Does anyone know how to do it?
http://jsbin.com/ipeseq/1/
Assuming that the change in case for name, major and sex is not an actual requirement, you can just push the object.
data.push(element);
As is you're basically creating a copy of the element piece by piece and pushing that, why not just push the element itself?

Categories

Resources