New to JSON so I'll do my best here. I have a JSON object called HUDS. Below are 2 sample nodes (by the way, can I call these nodes in JSON like in XML?).
var HUDS = [
{
"DISTRICT": "100",
"BIOS": "BROWN",
"AREA_KM": "3663.158164",
"AREA_MI": "1414.347616",
"NAME": "100",
"REG": "1",
"ACRES": "905182",
"EMU_Name": "Purcell",
"Shape_Leng": "299746.4938",
"Shape_Area": "3663158164",
},
{
"DISTRICT": "101",
"BIOS": "THIER",
"AREA_KM": "1507.774765",
"AREA_MI": "582.152762",
"NAME": "101",
"REG": "1",
"ACRES": "372578",
"EMU_Name": "Salish",
"Shape_Leng": "229150.0655",
"Shape_Area": "1507774766",
}
]
I have a drop down form that will be used to specify a value specific to the "BIOS" field in my JSON. For example the user could select BROWN from the dropdown menu.
I'd then like to create a var that can be used to fill in a div. For example when the user selects BROWN I'd like my div to fill with the value from "EMU_Name"
I know this is wrong but maybe it conveys what I am going for
function dropDownAction(){
var tempBios=document.BIOSForm.BIOS.value;
var tempEmuValue=HUDS.BIOS==tempBios.EMU_Name;
document.getElementById("mydiv").innerHTML=tempEmuValue;
}
Try:
<form name="BIOSForm">
<select name="BIOS" onchange="dropdownaction();">
<option value="BROWN">BROWN</option>
<option value="THEIR">THEIR</option>
</select>
</form>
<div id="emuname">
</div>
<script type='text/javascript'>
var HUDS = [
{
"DISTRICT": "100",
"BIOS": "BROWN",
"AREA_KM": "3663.158164",
"AREA_MI": "1414.347616",
"NAME": "100",
"REG": "1",
"ACRES": "905182",
"EMU_Name": "Purcell",
"Shape_Leng": "299746.4938",
"Shape_Area": "3663158164",
},
{
"DISTRICT": "101",
"BIOS": "THIER",
"AREA_KM": "1507.774765",
"AREA_MI": "582.152762",
"NAME": "101",
"REG": "1",
"ACRES": "372578",
"EMU_Name": "Salish",
"Shape_Leng": "229150.0655",
"Shape_Area": "1507774766",
}
]
function dropdownaction(){
for(var x=0;x<HUDS.length;x++){
var tempBios = document.BIOSForm.BIOS.value;
if(tempBios == HUDS[x].BIOS){
document.getElementById("emuname").innerHTML = HUDS[x].EMU_Name;
break;
}
}
}
</script>
Related
I am new to Vue js. I am trying to do an action form for the rest of API. I don't know how to get the data of name and location only. I was trying to use slice in Array, but it does not work.
My action form:
<div class="form-group">
<label class="required"> Social Media </label>
<b-form-checkbox v-for="event in events" :key="event._id" :value="event" v-model="selected">
{{event.name}}, {{event.location}}
</b-form-checkbox>
<span class="mt-3">Selected: <strong>{{ selected }}</strong></span>
</div>
My Vue instance
export default {
data() {
return {
events: [{
"_id": "d4d81da6-b453-4a31-999f-a2ea04848ee9",
"name": "A",
"location": "US",
"__v": 0
},
{
"_id": "91205d34-4480-4e4e-bdf7-fe66e46922b0",
"name": "B",
"location": "Korea",
"__v": 0
},
{
"_id": "0b168c44-4f38-4f86-8ee6-e077333aca95",
"name": "C",
"location": "Japan",
"__v": 0
}],
selected: ''
};
}
}
The Output when checking the first option of the checkbox:
Selected: ["_id": "d4d81da6-b453-4a31-999f-a2ea04848ee9", "name": "A", "location": "US", "__v": 0]
Expected output when checking the first option of the checkbox:
Selected: [ "name": "A", "location": "US" ]
You can create the necessary structure within the :value="" assignment.
<b-form-checkbox v-for="event in events" :key="event._id" :value="{ name: event.name, location: event.location }" v-model="selected">
{{event.name}}, {{event.location}}
</b-form-checkbox>
Firstly make Selected:false boolean ... then make a button and on click it'll get to a function which will accepts a parameter, iterate your array and select an object which is matching with the parameter
private selectFun(item){this.events.filter(val=>{val._id===item._id})//and then whatever}
[
{
"model":"products.productstable",
"pk":1,
"fields":{
"company":"STANDARD",
"description":"CHAKKARS BIG ",
"type":"Chakkars",
"productcase":1,
"quantity":100,
"units":"PKT",
"rate":150.0,
"retension":3.0,
"newrate":154.5,
"myretension":30.0,
"finalrate":200.85,
"retailrate":401.7,
"remarks":"ABC"
}
},
{
"model":"products.productstable",
"pk":2,
"fields":{
"company":"STANDARD",
"description":"SMALL",
"type":"Sparkler",
"productcase":1,
"quantity":100,
"units":"PKY",
"rate":100.0,
"retension":3.0,
"newrate":103.0,
"myretension":25.0,
"finalrate":128.75,
"retailrate":257.5,
"remarks":"SCDC"
}
}
]
If you want to display in template, you can use *ngFor as
<div *ngFor="let item of name">
<h2>Company: {{item.fields?.company}}</h2>
<p>Description: {{item.fields?.description}}</p>
<p>Type: {{item.fields?.type}}</p>
<p>Rate: {{item.fields?.rate}}</p>
</div>
Demo https://stackblitz.com/edit/angular-ejf6dw
You can simply use the es6 map function to create an instance of your array and retrieve the data fields.
export class SomeComponent implements Oninit{
ngOnInit(){}
someData =
[{"model": "products.productstable", "pk": 1, "fields": {"company": "STANDARD", "description": "CHAKKARS BIG ", "type": "Chakkars", "productcase": 1, "quantity": 100, "units": "PKT", "rate": 150.0, "retension": 3.0, "newrate": 154.5, "myretension": 30.0, "finalrate": 200.85, "retailrate": 401.7, "remarks": "ABC"}}, {"model": "products.productstable", "pk": 2, "fields": {"company": "STANDARD", "description": "SMALL", "type": "Sparkler", "productcase": 1, "quantity": 100, "units": "PKY", "rate": 100.0, "retension": 3.0, "newrate": 103.0, "myretension": 25.0, "finalrate": 128.75, "retailrate": 257.5, "remarks": "SCDC"}}]
// create a function within your class like
showfields(){
const fields = this.someData.map((data) => console.log(data.fields));
return fields;
}
// Call the showfield() function to perform the task
}
Demo: https://stackblitz.com/edit/angular-tpxp1j
You can just make the api call, and map the result to get the pk and field attribute.
this.myService.getFromAPI().subscribe(response => {
if (response && response.length) {
this.formattedResponse = response.map(item => {
return {
pk: item.pk,
fields: item.fields
};
});
console.log('rs', this.formattedResponse);
}
});
Complete demo code: https://stackblitz.com/edit/angular-c9ppa9
I have two four dropdowns, second dropdown selected and if I select first dropdown, second dropdown populates the value but shows last element first instead of first
sample data get the dropdown values
var countrydata ={
countries:[{
"country_code": "TH",
"country_name": "Thailand",
"currency_from": [
"THB",
"USD"
],
"currency_to": [
"THB"
],
"popular_to": [
"Malaysia",
"Myanmar"
],
"name": {
"en": "Thailand",
"th": "ประเทศไทย"
},
"normalized_name": {
"en": "thailand"
}
},
{
"country_code": "SG",
"country_name": "Singapore",
"currency_from": [
"SGD",
"USD"
],
"currency_to": [
"SGD"
],
"popular_to": [
"India",
"United States"
],
"name": {
"en": "Singapore",
"fr": "Singapour",
"zh": "新加坡"
},
"normalized_name": {
"en": "singapore"
}
}]
}
var currencydata = {
currencies:[{
"currency": "SGD",
"country_code": "SG",
"country_name": "Singapore",
"name": {
"en": "Singapore Dollar",
"fr": "Dollar Singapour",
"zh": "新加坡元"
},
"default_amount": "1000"
},
{
"currency": "THB",
"country_code": "TH",
"country_name": "Thailand",
"name": {
"en": "Thailand Baht",
"th": "เงินบาทไทย"
},
"default_amount": "9000"
},
}]}
index.js file sample
updateSendCountry(value) {
this.sendvalue = this.countrydata.countries.filter(function (item) {
return item.country_code == value;
})
if (this.sendvalue && this.sendvalue[0].currency_to) {
var sendcurrency = this.sendvalue[0].currency_to[0];
this.updateSendCurrency(sendcurrency);
}
}
updateSendCurrency(e) {
this.ccyvalue = this.currencydata.currencies.filter(function (item) {
return item.currency == e;
})
}
<select name="send_country" class="form-control" id="send_country" #change="${this.sendcountryChange}">
${this.countrydata.countries.map((country, key) => html`<option value=${country.country_code}>${country.country_name}</option>`)}
</select>
</div>
<div class="input-group p-2">
<div class="input-group-prepend">
<select name="sccy" class="form-control" id="sccy" #change="${this.updateSendCurrency}">
${this.sendvalue.map((currency) => currency.currency_from.map((send) =>
html`<option value=${send}>${send}</option>`))
}
</select>
eg:
Dropdown A -> Singapore populates Dropdown B -> SGD, USD
Dropdown A -> Thailand populates Dropdown B -> THB, USD
if dropdown A selection shows Singapore, SGD USD in Dropdown B
if USD selected in Dropdown B then i change Dropdown A to thailand it Dropdow B
populates THB, USB but shows USD first(second option) rather than THB
this.sendvalue.map(...) is going to update the state (attributes and content) of the <option> elements, but it won't necessarily replace them. This means that when you change the list, the first option will have its text changed from SGD to THB, but the second option (USD) will still be selected.
If you want to control the selection state, you'll need to store it and use something like this for your item template:
this.sendvalue.map((currency, index) => currency.currency_from.map((send) =>
html`<option value=${send} ?selected=${index === selectedIndex}>${send}</option>`))
Here I'm using a variable selectedIndex to store the selected index. You'd have to reset it when changing the country.
I'm building a dependent dropdown for country, state and city. It's not going very well. I've done extensive research on the subject on Stackoverflow and other sites on the web for the past few days and have not been able to get the '#state' select object to populate states based on the selected '#country' select object which is populating countries from json just fine. The states are not populating after the country is selected based on the 'change' method. I have an 'if' statement which says, 'if the selected #country === 'US' (which displays as North America), then load the US states and territories .json file.
After fiddling around with the code, I have finally been able to get the '#state' dropdown to at least display 'object [Object]', so I know I'm getting closer to a solution. I'm not quite sure why it's displaying 'object[Object]' in the state dropdown. It may be a 'type' error of some sort where json is being displayed as an object instead of a string as it should but I don't understand how to fix this in the context of my code.
Any help would be greatly appreciated.
Here is the HTML:
<!doctype html>
<html>
<head>
<title>Country->State->City</title>
</head>
<body>
Country:
<select id="country">
<pre><option selected value="base">Select Country</option><pre>
</select>
State:
<select id="state">
<option selected value="base">Select state</option>
</select>
City:
<select id="city">
<option selected value="base">Select City</option>
</select>
<script type = "text/javascript" src="jquery-2.2.4.min.js"></script>
<script type = "text/javascript" src="custom.js"></script>
</body>
</html>
jQuery
$(function(){
let countryOptions;
let stateOptions;
let gaCitiesOps;
$.getJSON('countries.json',function(data){
$.each(data, function(i,country) {
countryOptions+=
'<option value= "'+country.code+'">'
+country.name+
'</option>';
});
$('#country').html(countryOptions);
});
$("#country").change(function(){
if($(this).val()==="US"){
$.getJSON('us_states.json',function(data){
$.each(data, function(stateCode,stateName) {
stateOptions+='<option value="'+stateCode+'">'
+stateName+
'</option>';
});
$('#state').html(stateOptions);
});
}
});
$("#state").change(function(){
if($(this).val()==="GA"){
$.getJSON('GA_cities.json',function(data){
$.each(data, function(statecode,city) {
gaCitiesOps +='<option value="'+statecode+'">'
+city+
'</option>';
});
$('#city').html(gaCitiesOps);
});
}
});
});
Countries.json
[
{
"code": "US",
"name": "North America"
},
{
"code": "AG",
"name": "Antigua"
},
{
"code": "AU",
"name": "Australia"
},
{
"code": "AT",
"name": "Austria"
},
{
"code": "BG" ,
"name": "Bulgaria"
},
{
"code": "CA",
"name": "Canada"
},
.....ect
us_states.json
[
{
"stateCode": "AL",
"name": "Alabama"
},
{
"stateCode": "AR",
"name": "Arkansas"
},
{
"stateCode": "AS",
"name": "American Samoa"
},
{
"stateCode": "AZ",
"name": "Arizona"
},
{
"stateCode": "CA",
"name": "California"
},
.....etc
GA_cities.json
[
{
"code": "ALB",
"name": "ALBANY"
},
{
"code": "AMR",
"name": "AMERICUS"
},
{
"code": "ATH",
"name": "ATHENS"
},
{
"code": "ATL",
"name": "ATLANTA"
},
{
"code": "AUG",
"name": "AUGUSTA"
},
{
"code": "BAI",
"name": "BAINBRIDGE"
},
....etc
Thanks for your consideration!
You're using $.each incorrectly. First argument is the index/key, second is the value. In your case you iterate over array of objects - so first argument is an index and second is each contained object. Use this code for states:
$.each(data, function(index,stateObj) {
stateOptions+='<option value="'+stateObj.stateCode+'">'
+stateObj.name+
'</option>';
});
$('#state').html(stateOptions);
});
And this for cities:
$("#state").change(function(){
if($(this).val()==="GA"){
$.getJSON('GA_cities.json',function(data){
$.each(data, function(index,city) {
gaCitiesOps +='<option value="'+city.code+'">'
+city.name+
'</option>';
});
$('#city').html(gaCitiesOps);
});
}
});
You can also add options using JS APIs which is slightly better than constructing the entire options HTML as a string and dumping it into html(). See this question for the alternative methods.
console.log() is your best friend. Try logging the values you get from $.each and you will know why you're getting [object Object].
$.each(data, function(stateCode, stateName));
Output is stateCode 0, stateName {stateCode: "AL", name: "Alabama"}
$.each arguments are (key, value) and you are looping over an array so key (stateCode in this case) is index of the array.
ES6; If you wanna be fancy you can destructure the arguments to
$.each(key, {stateCode, name});
I currently have a product page where user can add items to a basket. Once the item is added its stores the product ID in the local storage. I would like to be able to then add all the items they selected to the cart page, displaying the price, name and image. I'm not really sure how to go about this, please could you help me out.
data structure with each product having a unique ID:
{
"products": [{
"id": "0",
"name": "Logitech G910 Orion Spectrum RGB Mechanical Gaming Keyboard - UK-Layout",
"price": "119.99",
"category": "0",
"description": "Logitech 920-008017 G910 Orion Spectrum RGB Mechanical Gaming Keyboard - Black.",
"images": [{
"id": "0",
"src": "images/00.jpg"
},
{
"id": "1",
"src": "images/01.jpg"
},
{
"id": "2",
"src": "images/02.jpg"
}
]
},
Code that adds an item to a basket:
$('#myTable').on('click', '.cartbutton', function() {
var row = $(this).parents('tr');
console.log(row.attr('id'), row.data('price'));
added.push(row.attr('id'));
localStorage.setItem("cartItems", JSON.stringify(added));
var storeddata=localStorage.getItem("cartItems");
console.log(storeddata);
})
A example of the resulting array:
["0", "0", "0", "1", "1"]
You can iterate the array when you need to list the products like
var products = //Your Product Array
for(var i in storeddata)
{
var id = storeddata[i];
var obj = products.filter(function ( obj ) {
return obj.id === id;
})[0];
console.log(obj);//This will be you product
}