Chained State city dropdown list from JSON - json

I am trying to populate a chained State City select dropdowns. I am using an external json file to do so, which consists of State and their corresponding city name, id and pincode. Can somebody gimme some idea on how to achieve this. I need to populate the city and pincode value based on the state selection. Thanks in advance...
JSON
{
"Alaska" : [
{"id": "1", "name": "Adak", "pincode": "xxx1"},
{"id": "2", "name": "Akhiok", "pincode": "xxx2" },
{"id": "3", "name": "Akiak", "pincode": "xxx3" },
],
"Arizona" : [
{"id": "4", "name": "Apache Junction", "pincode": "xxx4"},
{"id": "5", "name": "Avondale", "pincode": "xxx5"},
{"id": "6", "name": "Benson", "pincode": "xxx6"},
],
"Alabama" : [
{"id" : "5", "name": "Abbeville", "pincode": "xxx7" },
{"id" : "7", "name": "Adamsville", "pincode": "xxx8" },
{"id" : "8", "name": "Akron", "pincode": "xxx9" },
]
}
Final rendered html
<select id="state">
<option value="1">Alaska</option>
<option value="2">Arizona</option>
<option value="3">Alabama</option>
</select>
<select id="city">
<option value="4">Adak</option>
<option value="5">Akhiok</option>
<option value="6">Akiak</option>
</select>
<input id="pincode" type="text" />

I find your question interesting and wrote the corresponding solution which you can see live here.
Here is the code:
jQuery(document).ready(function () {
var myData;
var onCityChange = function (e) {
var cityData = $("option:selected", e.target).data('pincode');
$("#pincode").val(cityData.pincode);
};
var onStateChange = function (e) {
var state = $("option:selected", e.target).text();
if (state && myData) {
var stateData = myData[state];
if (stateData && stateData.length > 0) {
$("#city").empty();
$("#city").unbind('change');
for (var i = 0; i < stateData.length; i++) {
var cityData = stateData[i];
var option = $('<option value="' + cityData.id + '">' + cityData.name + '</option>')
.data('pincode', cityData);
$("#city").append(option);
}
$("#city").bind('change', onCityChange)
.trigger('change');
}
}
};
$.ajax({
url: 'DependendSelectsFromJson.json',
dataType: 'json',
success: function (data) {
var stateOptions = "", stateId = 1;
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
stateOptions += '<option value="' + stateId + '">' + prop + '</option>';
stateId++;
}
}
myData = data;
$("#state").html(stateOptions)
.bind('change', onStateChange)
.trigger('change');
}
});
});
to get access about the pincode of the second (city) select box I used jQuery.data function which I find very practical if one need to associate some additional information with an DOM element. One could save only pincode value in the way, but I used the function to save full information about the city.
UPDATED: I forgot to mention that the JSON data which you posted has errors. You should remove commas before ']'. Probably it is just a problem with cut&paste of the data to the text of the question.

there are many ways.
global Varible option.
var json_object = {
"Alaska" : {}
}; //and the rest of other text too lazy to type :)
$('#state').change(function(){
var state = $(this).val();
cities = json_object[state];
$('#city').html('');//remove the prev elements
for(item in cities){//same as foreach in php
$('<option value=""></option>').appendTo($('#city'));
}
});
i must admit is not complete but giving you the rough idea.
Other wise use ajax like so
$('#state').change(function(){
var url = 'ajax.php';//should return json with a list of cities only
var state = $('#state').val();
var data = {'state':state};
$.ajax({
url:url,
data:data,
dataType:'json',
success: function(items){
//do something with it
}
})
});
The only thing you need to know is that both have their advantages and disadvantages.
first option : can only fire one request but loads sh*t loads of data that are not needed.
second option: makes more request but less data

Related

referencing objects in JSON

I have a code as a shown below in which I am not sure how to do referencing.
<p id="demo" ></p>
<p id="options"></p>
<script>
var myObj, myJSON, text, obj;
myObj = {
"quiz": {
"sport": {
"q1": {
"question": "Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Los Angeles Kings",
"Golden State Warriros",
"Huston Rocket"
],
"answer": "Huston Rocket"
}
},
"maths": {
"q1": {
"question": "5 + 7 = ?",
"options": [
"10",
"11",
"12",
"13"
],
"answer": "12"
}
}
}
}
//Storing data:
// converting JS object into String
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
//Retrieving data:
text = localStorage.getItem("testJSON");
//converting String into JS object
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = // code
Problem Statement:
I am wondering what changes should I make in the below line(which is the last line in the above code) so that the output should be Huston Rocket.
document.getElementById("demo").innerHTML = // code
I tried in the following way but somehow I am not able to reach Huston Rocket
document.getElementById("demo").innerHTML = myObj.quiz.sport.q1.answer;
You are using incorrect name, after Json parsing, your Json object is 'obj'
So use it as
document.getElementById("demo").innerHTML = obj.quiz.sport.q1.answer;

Add value of key that will be pushed to an array Angular

The value inside the input and textarea should be pushed the entire JavaScript part works, but how can I bind the ng-model so that Angular will pick up the value of entered information and push that into an array. Anyone an idea how to do that in HTML.
angular.module("forum-page", ["myApp"])
.controller("Forum", function($scope) {
$scope.comments = [
{
"name": "Kevin",
"comment": "Wat een mooi toestel vandaag ontvangen, zeer blij met mijn bestelling :)",
"country": "Nederland"
},
{
"name": "Jason",
"comment": "What a great phone I received from Meizu, will surely come back to buy again in the future",
"country": "USA"
},
{
"name": "姚宣辰",
"comment": "這個手機很標亮, 下次也會買魅族智能手機",
"country": "中国"
},
];
$scope.addComment = function() {
$scope.comments.push({ "name": $scope.name, "comment": $scope.comment, "country": $scope.country});
var dataObj = {
name: $scope.name,
comment: $scope.comment,
country: $scope.country
};
$scope.dataObj = dataObj;
res.error(function(data, status, header, config) {
alert("failure message: " + JSON.stringify({data: data}));
});
$scope.name = "";
$scope.comment = "";
$scope.country = "";
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<input type="text" class="comment-box-name" ng-model="{{dataObj.name}}"/>
<input type="text" class="comment-box-comment" ng-model="{{dataObj.comment}}"/>
<textarea type="text" class="comment-box-country" ng-model="{{dataObj.country}}"></textarea>
<button ng-click="addComment()">Place comment</button>
No you cannot do that if you want that kind of automation in the template. In order to do that kind of action you need to place that action inside your click event listener which acts as the send button.
$scope.addComment = function () {
// Add validations before proceeding
theArray.push(dataObj);
}
Hope that helps
Some changes needed in your code :
1. remove {{}} from the ng-model value.
use dataObj.name,dataObj.comment,dataObj.country instead of {{dataObj.name}},{{dataObj.comment}},{{dataObj.country}}
2. use $scope object instead of var to initialize the object to perform the two way data binding.
$scope.dataObj = {
name: $scope.name,
comment: $scope.comment,
country: $scope.country
};
Demo!

How to display JSON data in html page using ng-repeat in AngularJS?

I have one JSON data how to display these data using ng-repeat?
I am new in angularJS. I dont how to to repeat nested in ng-repeat in angularJS
This is my JSON data.Please help me to show the outputs?
How to get these data using ng-repeat
customerId=56b6f841d085980f2241909c
name: Maxxwell
Total Product=2
Total Price=685 //(2*18.5)+240(3*(240*10/100))
createdOn: 07-Feb-2016 10:50:05 UTC
etc....
See $scope.orders is an array
I call an api and got this data
orderPromise.success(function(data, status, headers, config)
{
$scope.orders=
[
{
"customerId": "56b6f841d085980f2241909c",
"address": {
"name": "Maxxwell",
"city": "Texas",
"country": "USA",
},
"products": [
{
"productId": "569df8bcd08598371e9b5ad9",
"quantity": 2,
"productDetails": {
"itemId": "569df86dd08598371e9b5ad8",
"actualPrice": "18.5",
"offer": 0,
"modifiedOn": "19-Jan-2016 12:35:32 UTC"
}
},
{
"productId": "569f2d2dd085980ecfc8997b",
"quantity": 3,
"productDetails": {
"itemId": "569f294dd085980ecfc89971",
"actualPrice": "240",
"offer": 10,
"modifiedOn": "06-Feb-2016 09:09:46 UTC"
}
}
],
"createdOn": "07-Feb-2016 10:50:05 UTC"
}
]
});
I need to display this output using ng-repeat in html page
customerId=56b6f841d085980f2241909c
name: Maxxwell
Total Product=2
Total Price=685 //(2*18.5)+240(3*(240*10/100))
createdOn: 07-Feb-2016 10:50:05 UTC
:
:
I don't know its correct or not but its not working in my html page
Please correct me if it is wrong?
$scope.ordertemp=[];
$scope.orderval={};
var countval = $scope.orders.length;
for(var j=0;j<countval;j++)
{
$scope.orderval.buyerId = $scope.orders[j].customerId;
$scope.orderval.name = $scope.orders[j].address.name
$scope.orderval.totalitem = $scope.orders[j].products.length
var count = $scope.orders[j].products.length
var total = 0;
var save=0;
for(var i=0;i<count;i++)
{
var actualprice = 0;
var offer = 0;
var price = 0;
var quantity=0;
actualprice = $scope.orders[j].products[i].productDetails.actualPrice;
offer = $scope.orders[j].products[i].productDetails.offer;
quantity = $scope.orders[0].products[i].quantity;
price = actualprice - (actualprice * offer)/100
total = total + (price * quantity);
save = save +((actualprice/100)*offer)* quantity
}
}
$scope.orderval.totalprice = total;
$scope.orderval.save = save;
$scope.ordertemp.push($scope.orderval);
alert(JSON.stringify($scope.ordertemp));
When i alert this data will shown but its not repeated in my ui page Why?
Can i add any filter for using this to add Total price?
you can also do like this,First flatten your response as your need. Like below
$scope.orders=
[
{
"customerId": "56b6f841d085980f2241909c",
"address": {
"name": "Maxxwell",
"city": "Texas",
"country": "USA",
},
"products": [
{
"productId": "569df8bcd08598371e9b5ad9",
"quantity": 2,
"productDetails": {
"itemId": "569df86dd08598371e9b5ad8",
"actualPrice": "18.5",
"offer": 0,
"modifiedOn": "19-Jan-2016 12:35:32 UTC"
}
},
{
"productId": "569f2d2dd085980ecfc8997b",
"quantity": 3,
"productDetails": {
"itemId": "569f294dd085980ecfc89971",
"actualPrice": "240",
"offer": 10,
"modifiedOn": "06-Feb-2016 09:09:46 UTC"
}
}
],
"createdOn": "07-Feb-2016 10:50:05 UTC"
}
]
Now code for flatten the response
var myFinalArr = [];
for (index in $scope.orders) {
var obj = {};
var productSum = 0;
obj.customerId = $scope.orders[index].customerId;
obj.name = $scope.orders[index].address.name;
obj.city = $scope.orders[index].address.city;
obj.country = $scope.orders[index].address.country;
obj.createdOn = $scope.orders[index].createdOn;
obj.productCount = $scope.orders[index].products.length;
for (index2 in $scope.orders[index].products) {
productSum = parseFloat(productSum) + parseFloat($scope.orders[index].products[index2].productDetails.actualPrice);
if (index2 == ($scope.orders[index].products.length) - 1) {
obj.productSum = productSum;
}
}
myFinalArr.push(obj);
}
console.log(myFinalArr);// your final Arr
$scope.orders = myFinalArr;
})
In view use this
<div ng-repeat = "orderData in orders">
<div>CustomerId : {{orderData.customerId}}</div>
<div>Name : {{orderData.name}}</div>
<div>Total Product : {{orderData.productCount}}</div>
<div>Total Price : {{orderData.productSum}}</div>
<div>CreatedOn : {{orderData.createdOn}}</div>
</div>
You can do :
<div ng-repeat="order in orders">
<div>
customerId={{order.customerId}}
</div>
<div>
name:{{order.address.name}}
</div>
<div>
Total product={{order.products.length}}
</div>
</div>
And you'll need a function or a watch to get the total of your products.
If you give me a Plnkr or Jsfiddle link with a working sample I could probably provide a more complete answer if you need.
Happy coding!
try this
<div ng-repeat="(key, value) in orders">
<p>{{value.customerId}}</p>
<p>{{value.createdOn}}</p>
<p>{{value.address.name}}</p>
<div ng-repeat="(key, provalues) in value.products">
<p>{{provalues.quantity}}</p>
<p>{{provalues.productDetails.actualPrice}}</p>
</div>
</div>
To display json Data in html add json filter to your expression like
<div ng-repeat="order in revoluza = (orders | json)">
<div>
customerId={{order.customerId}}
</div>
<div>
name:{{order.address.name}}
</div>
<div>
Total product={{order.products.length}}
</div>
</div>
Please find the clear answer below
html part
<div ng-repeat="(key,value) in accounttypes">
<ul><li ng-repeat="account in value.services">{{account.types}}</li></ul>
</div>
js part
bankservice.findByaccounttype($scope.selectedservice).then(function(results)
{
$scope.accounttypes = results;
});
function bankservice($q)
{
var accountservice=[{"id":"1","title":"Savings Account","services":[{"types":"ATM card request"},{"types":"loan request"}]},
{"id":"2","title":"Current Account","services":[{"types":"cheque book request"},{"types":"ATM card request"}]},
{"id":"3","title":"Demat Account","services":[{"types":"loan request"},{"types":"ATM card request"}]}];
return {
findAll: function() {
var deferred = $q.defer();
deferred.resolve(accountservice);
return deferred.promise;
},
findByaccounttype: function (selectedservice) {
var deferred = $q.defer();
var results = accountservice.filter(function (element) {return selectedservice === element.title;
});
deferred.resolve(results);
return deferred.promise;
}
}
}

Json response + Node.js

In my node app i pass bunch of queries as Object.I have to form as exact format of request.
Consider my request as:
{q0:{query0},q1:{query1},q2:{query1}}
My reponse should be {q0:{response0},q1{response1},q2{response2}
My actual query(In my app):
{"q0":{"query":"James Madison","type":"/people/presidents","type_strict":"should"},
"q1":{"query":"George Washington","type":"/people/presidents","type_strict":"should"},
"q2":{"query":"John Adams","type":"/people/presidents","type_strict":"should"},
"q3":{"query":"James Monroe","type":"/people/presidents","type_strict":"should"},
"q4":{"query":"Thomas Jefferson","type":"/people/presidents","type_strict":"should"}}
But my response is coming as:
{"result":[q0result,q1result,q3result]}
My code:
for (var id in presidents ) {
var match
if (query == presidents[id]) {
//console.log(" Inside match")
match = true;
}
else {
match = false;
}
matches.push({
"id": id,
//"name": name,
"score": 100,
"match": match,
"type": [{
"id": "/people/presidents",
"name": "US President"
}]
})
}
callback(matches);
json = JSON.stringify({"result":matches});
res.writeHead(200, {'content-type':'application/json'});
res.end(json);
Please help me to solve this..Thanks in advance.
You are pushing the result in an array instead you should create a property in the result object as below
var matches = {};
for (var id in presidents ) {
if (query == presidents[id]) {
//console.log(" Inside match")
match = true;
}
else {
match = false;
}
matches[id] ={
"id": id,
//"name": name,
"score": 100,
"match": match,
"type": [{
"id": "/people/presidents",
"name": "US President"
}]
};
}
callback(matches);

How to receive a json string after a jquery post in WebMatrix?

If I have the following post call:
$('#json_form').submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = {
"uno": "lalala",
"dos": "jojojo"
}
var data = JSON.stringify(datos);
$.post(url, data, function (resultado) {
$('#posted_values').html(resultado);
});
});
How can I receive and process the json object in a cshtml file? I mean what I put in Decode call:
if (IsPost)
{
var json_object = Json.Decode(Request???);
}
Edited to complete the answer of #MikeBrind, to help others with the same problem.
Example of using decode for a more complex json object.
$('#json_form').submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = {
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumber": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
var data = JSON.stringify(datos);
$.post(url, {"person": data}, function (resultado) {
$('#posted_values').html(resultado);
});
});
Receiving and using:
#{
dynamic json_object;
if (IsPost)
{
json_object = Json.Decode(Request["person"]);
#json_object.firstName<br/>
#json_object.lastName<br/>
#json_object.address.city<br/>
#json_object.address.postalCode<br/>
foreach (dynamic phone in json_object.phoneNumber)
{
#phone.type<br/>
#phone.number
}
}
}
Don't JSON.stringify the data if it is just key/value pairs like this. Do a form post:
$('#json_form').submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = {
"uno": "lalala",
"dos": "jojojo"
}
//var data = JSON.stringify(datos); no need for this
$.post(url, datos, function (resultado) {
$('#posted_values').html(resultado);
});
});
Then the values are available from Request["uno"] and Request["dos"]
If you ever do need to use JSON.stringify (which you would for more complex data structures), the JSON is transmitted in the Request body, so you need to extract it from Request.InputStream:
var reader = new StreamReader(Request.InputStream);
var json = reader.ReadToEnd();