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();
});
Related
Hi (sorry for my english), I have this script:
<script type="text/javascript">
$(document).ready(function() {
var idPlato = decodeURI(getUrlVars()["idPl"]);
var url = "http://localhost/plato-datos.php?idPla="+idPlato+"";
});
};
</script>
It brings me this json from my database:
[{"category":"first","name":"green","idP":"1", "count":3},
{"category":"first","name":"blue","idP":"2","count":5},
{"category":"sec","name":"peter","idP":"3", "count":3},
{"category":"sec","name":"james","idP":"4", "count":2,},
{"category":"third","name":"dog","idP":"5", "count":4}]
I need to create one radiobuton for every name and group by categores
I create a solution. Kinda ugly but it will work:
var data = [{
"category": "first",
"name": "green",
"idP": "1",
"count": 3
}, {
"category": "first",
"name": "blue",
"idP": "2",
"count": 5
}, {
"category": "sec",
"name": "peter",
"idP": "3",
"count": 3
}, {
"category": "sec",
"name": "james",
"idP": "4",
"count": 2,
}, {
"category": "third",
"name": "dog",
"idP": "5",
"count": 4
}];
var result = {};
data.map(a => {
if (result[a.category]) {
result[a.category].push(a.name);
} else {
result[a.category] = [a.name];
}
});
Object.keys(result).map(category => {
var select = document.createElement('select');
result[category].map(name => {
var option = document.createElement('option');
option.value = name;
option.text = name;
select.appendChild(option);
});
document.body.appendChild(select);
});
Im working with jquery mobile then i used autodividersSelector function for group by the category JSON object, and build a radiobuton for every name
<script type="text/javascript">
//catch the JSON from my database
$(document).ready(function() {
var idPla = decodeURI(getUrlVars()["idPl"]);
var urlAder =
"http://localhost/lista-adereso.php?idPla=" + idPla + "";
//print the radiobutons
$.getJSON(urlAder, function(resultado) {
var allfiles = '';
for (var i = 0, aderesos = null; i <
resultado.length; i++) {
aderesos = resultado[i];
allfiles +='<li><label><input type="radio" data-
status="' + aderesos.aderesoCatNom +'"
name="name" id="id" value="' +
aderesos.aderNombre +'">'+
aderesos.aderNombre + '</label></li>'; }
//Group by categories
$('#linkList')
.empty()
.append(allfiles)
.listview({
autodividers:true,
autodividersSelector: function ( li ) {
var out = li.find('input').data("status");
return out;
}
})
.listview("refresh");
});
});
</script>
I have an array of objects , each object have key and value .I want if object have same keys then their values shoud be comma sepated of all the values of same key.
my html code:
<p ng-repeat="item in allOptions" class="item" id="{{item.id}}">
{{item.id}} <input type="checkbox" ng-change="sync(bool, item)" ng-model="bool" > {{item}} Selected: {{bool}}
</p>
and my controller code is :
$scope.allOptions = [
{
"id": "1",
"data": "one",
},
{
"id": "1",
"data": "two",
},
{
"id": "2",
"data": "three",
},
];
$scope.data = [
];
$scope.sync = function(bool, item){
if(bool){
// add item
$scope.data.push(item);
} else {
// remove item
for(var i=0 ; i < $scope.data.length; i++) {
if($scope.data[i] == item.id){
$scope.data.splice(i,1);
}
}
}
};
In data array i have objects ,if we select same key of objects (same id value )then i want
{
"id": "1",
"data": "one","two",
}
var myData = [{
"id": "1",
"data": "one",
},{
"id": "1",
"data": "two",
},{
"id": "2",
"data": "three",
}];
var output = [];
//Iterating each element of the myData
myData.forEach(o => {
//Checking the duplicate value and updating the data field
let temp = output.find(x => {
if (x && x.id === o.id) {
x.data += ", " + o.data;
return true;
}
});
if(!temp)
output.push(o);
});
console.log(output);
I think, easiest way to make it would be like:
z = [
{
"id": "1",
"data": "one",
},
{
"id": "1",
"data": "two",
},
{
"id": "2",
"data": "three",
},
];
And immediate code:
var result = {};
var groupedO = {};
for(a in z){
var id = z[a].id;
var data = z[a].data;
if(groupedO[id] && groupedO[id].data){
groupedO[id].data = groupedO[id].data + ',' + data;
} else {
groupedO[id] = {data:data};
}
}
for(ind in groupedO) {
var el = groupedO[ind];
if(el.data.split(',').length > 1) { // here we take only last those, where many datas grouped in
result.id = ind;
result.data = el.data;
}
}
After this, result will look like:
{ id: "1", data: "one,two" }
If you use jQuery, then you can use $.extend() function in this code if you don't want to put reference to the object item in array hash. This means that if you change the object item in array hash, then object item in array myData change too. To avoid this, use $.extend() function.
var myData = [
{
"id": "1",
"data": "one",
},
{
"id": "1",
"data": "two",
},
{
"id": "2",
"data": "three",
},
]; // this will be your input data
function filterData(collection) {
var hash = {};
var result = [];
collection.forEach(function (item) {
if (hash[item.id]) {
hash[item.id].data += ', ' + item.data;
}
else {
hash[item.id] = $.extend({}, item);
}
});
for (var i in hash) {
result.push(hash[i]);
}
return result;
}
var filteredData = filterData(myData); //your filtered data
You can do this in following manner:
var myData = [{
"id": "1",
"data": "one",
},
{
"id": "1",
"data": "two",
},
{
"id": "2",
"data": "three",
},
]; // this will be your input data
function filterData(collection) {
var hash = {};
var result = [];
collection.forEach(function(item) {
if (hash[item.id]) {
hash[item.id].data += ', ' + item.data;
} else {
hash[item.id] = item;
}
});
for (var i in hash) {
result.push(hash[i]);
}
return result;
}
console.log(
filterData(myData) //your filtered data
)
I have below json array structure.. How can i get the key and value of each of the records json object?
{
"records": [{
"cfsub_2": "1",
"cf_7": "1/3/2016",
"cf_1": "Clinic San",
"cf_2": "Fever",
"cf_3": "56.60",
"cfe_8": "dsf4334"
}, {
"cfsub_2": "2",
"cf_7": "3/3/2016",
"cf_1": "Clinic Raju",
"cf_2": "braces",
"cf_3": "183.50",
"cfe_8": "fresr4"
}]
}
My expected output is to get the key and value... below as example:
<b>key</b> : cf_1, <b>value</b> : Clinic San
I have tried to loop in the records, but since i don't know the key, so i unable to get the value..
for (var z in records)
{
var value = records[z].cf_1;
alert(value);
}
//i don't know the key here.. i want to get the key and value
The full JSON structure is as below:
{
"forms": [{
"id": 1,
"records": [{
"cfsub_2": "1",
"cf_7": "1/3/2016",
"cf_1": "Clinic San",
"cf_2": "Fever",
"cf_3": "56.60",
"cfe_8": "dsf4334"
}, {
"cfsub_2": "2",
"cf_7": "3/3/2016",
"cf_1": "Clinic Raju",
"cf_2": "braces",
"cf_3": "183.50",
"cfe_8": "fresr4"
}]
}, {
"id": 7,
"records": [{
"cf_31": "27/3/2016",
"cf_32": "Singapore",
"cf_33": "dfd555",
"cfe_34": ""
}]
}, {
"id": 11,
"records": [{
"cfsub_10": "9",
"cf_9": "25/3/2016",
"cf_10": "256.50",
"cfe_11": "dfg44"
}]
}]
}
Hope this one is helpful for you.
$.each(value.forms, function(index,array){
$.each(array.records, function(ind,items){
$.each(items, function(indo,itemso){
alert( "Key -> "+indo + " : values -> " + itemso );
});
});
});
var getKeys = function (arr) {
var key, keys = [];
for (i = 0; i < arr.length; i++) {
for (key in arr[i]) {
if (arr[i].hasOwnProperty(key)) {
keys.push(key);
}
}
}
return keys;
};
Sample data:
{
"data": [
{
"name": {
"full": "JOHN",
"rank": "SENIOR"
},
"mobile": "12345"
},
{
"name": {
"full": "HENRY",
"rank": "SENIOR"
},
"mobile": "67890"
},
{
"name": {
"full": "SAM",
"rank": "JUNIOR"
},
"mobile": "54321"
}
]
}
i'm trying to get the total number of senior members from the data sample above, and i can get the data.name and data.mobile, but i can't get the 'rank' data from the parent 'name' object. can anyone please guide me to obtain the rank data. below is my javascript:
function countRank(rank) {
var i;
for (i in rank.data) {
if (rank.data[i] == "SENIOR") {
i++;
}
document.getElementById('senior').innerHTML = 'Total senior members: ' + i;
}
}
<div id="senior"></div>
Try this JSFIDDLE
function countRank(rank) {
var k=0;
for (var i=0; i< rank.data.length; i++) {
if (rank.data[i].name.rank == "SENIOR") {
k++;
}
document.getElementById('senior').innerHTML = 'Total senior members: ' + k;
}
}
countRank(rank);
You can make something like this
var rank = {
"data": [{
"name": {
"full": "JOHN",
"rank": "SENIOR"
},
"mobile": "12345"
}, {
"name": {
"full": "HENRY",
"rank": "SENIOR"
},
"mobile": "67890"
}, {
"name": {
"full": "SAM",
"rank": "JUNIOR"
},
"mobile": "54321"
}]
};
function countRank(rank) {
var i = 0,
arr = rank.data;
for (var j = 0; j < arr.length; j++) {
for (var prop in arr[j]) {
if (arr[j][prop].rank == "SENIOR") {
i++;
}
document.getElementById('senior').innerHTML = 'Total senior members: ' + i;
}
}
}
countRank(rank);
myObject.data[0].name.rank
>>> "SENIOR"
Assuming that whole object is called obj:
var i=0;
for (i=0; i < obj.data.length; i++) {
console.log(obj.data[i].name.rank);
}
function countRank(rank) {
var count = 0;
var arr = rank.data;
for (var i=0; i<arr.length; i++) {
var name = arr[i].name;
if (name.rank == "SENIOR") {
count++;
}
}
alert(count);
}
I checked it and it worked well.
Using jQuery you can find rank from above data easily.
checkout sample on jsFiddle
http://jsfiddle.net/uBnfu/
$.each(jsonData.data, function (index, value) {
alert(value.name['rank']);
});
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?