Populate two select from JSON - javascript

This is my JSON file:
{
"AL2": {
"3810": "AL2GR1",
"3814": "AL2GR2",
"3815": "AL2GR3",
},
"AN3": {
"3818": "AN3GR1",
"3819": "AN3GR2"
},
"CME": {
"2405": "CME"
}
I need to populate two select boxes. The first one let choose between first level values (AL2,AN3,CME) and the second one between the deep level ones (AL2GR#,AN3GR#,CME).
My infile Javascript is :
var jsonData = {"AL2": {"3810": "AL2GR1","3814": "AL2GR2","3815": "AL2GR3"},"AN3": {"3818": "AN3GR1","3819": "AN3GR2"},"CME": {"2405": "CME"}};
$(window).load(function(){
$.each(jsonData,function(key, value) {
$('#ue').append('<option value=' + key + '>' + key + '</option>');
});
});
function grfromue(element,jsonData) {
var ue = $("#ue option:selected").text();
alert(ue);
$.each(jsonData[ue],function(key, value) {
$('#gr').append('<option value=' + key + '>' + value + '</option>');
});
};
And HTML :
<select id="ue" onChange="grfromue(this,jsonData);">
</select>
<select id="gr">
</select>
The second select box isn't changing, what am I doing wrong ?

Below snippet of code might be helpful to you
var json = {
"AL2": {
"3810": "AL2GR1",
"3814": "AL2GR2",
"3815": "AL2GR3",
},
"AN3": {
"3818": "AN3GR1",
"3819": "AN3GR2"
},
"CME": {
"2405": "CME"
}
};
to get each value in first level
$.each( json, function( key, value ) {
console.log( key );
});
to get second level values based on your first input
input = 'AL2';
$.each( json[input], function( key, value ) {
console.log( key + ' : ' + value );
});
Hope this helps you.

You can use a nested JQuery each method to iterate over the objects and the nested objects within them. You can extend it for as many nested objects as you like.
jQuery.each(obj, function(i, val) {
console.log("Object: " + i);
jQuery.each(val, function(j, value) {
console.log('It has ' + j + ' with value ' + value);
});
});
If you want to populate the second select box based on the value of the first, you can use array notation to fetch contents of the object. Something like this:
jQuery("#selec-id").change(function(){
$("#second-select-id").html("");
jQuery.each(obj[$(this).val()], function(key, value) {
$("#second-select-id").append("<option value='"+key+"'>"+value+"</option>");
});
});

Related

Unable to get this.value in this code

function showData(){
Object.keys(JSONcall).forEach(function(key){
var tvShow = JSONcall[key].show;
$('#show-select').append("<option class=\"selectS\"" +
"id=\"" + key + "\"" + "value=\"JSONcall[" + key + "]
.show\" onchange=\"selectShow(this.id)\">" + tvShow.name + "</option>");
});
}
Hello, I have this forEach loop where the function is to append the results of a JSON object. After appending the result is:
<option class="selectS" id="0" value="JSONcall[0].show"
onchange="selectShow(this.id)">Some Value</option>
First question: Is it wise to append onchange=(function()) like that?
selectShow(value) is a function meant to get id of <option> and display the data in another <div>.
Last question is why am I unable to get the results of this.id in this context?
create option element like this , and three is no need of id at option element as you are having val on option to identify it.
$('<option>').val(key).text(tvShow.name).appendTo('#show-select');
one more thing selectShow() must need to apply at to select not to option.
<select onchange= "selectShow()"> </select>
function selectShow(){
console.log($( "#show-select" ).val());
}
You have to put your onchange trigger on your select. I advice you to add event with javascript no in html attribute. You have to use value instead of id for sharing value.
const obj = {
channel1: {
show: {
id: "#ch1",
name: "ch1"
}
},
channel2: {
show: {
id: "#ch2",
name: "ch2"
}
}
};
function showData() {
$.each(obj, function(key, value) {
const tvShow = value.show; // obj[key] === value
$("<option></option")
.addClass("selectS")
.val(key)
.text(tvShow.name)
.appendTo("#show-select");
});
}
function selectShow() {
console.log($(this).val());
}
showData();
$("#show-select").on("change", selectShow)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="show-select"></select>
I have reworked your code in a different way.
Used $.ajax() to pull some random JSON data and parse it.
Used $.each(var, function(index, value) {}) to iterate over the object.
Used change() event to log text, val, id
The rest you can modify inside append() method.
function showData() {
$.ajax({
url: "https://www.json-generator.com/api/json/get/bHepFCoNmG?indent=2",
success: function(data) {
$.each(data, (i, val) => {
$("#mySelect").append('<option class="selectS" id="' + i + '" value="' + val.name + '">' + val.name + '</option>');
});
}
});
}
// change event
$('#mySelect').change(function() {
console.log($(this).find(':selected').text());
console.log($(this).find(':selected').val());
console.log($(this).find(':selected').attr("id"));
});
showData();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<select id="mySelect">
</select>
</div>
The code below shows how to use jQuery.data() to solve the same issue:
//TODO: Add triggers and events
function showData() {
// Retrieve JSON file from website
$.ajax({
// Returns 15 rows
url: "https://www.json-generator.com/api/json/get/cuScfPsQRK?indent=2",
success: function(data) {
// Iterate retrieved JSON Object
$.each(data, (i, val) => {
// Get JSON keys
let key = val.key;
let value = val.value;
// Define metadata object
let metaData = JSON.stringify({
index : i,
key : key,
value : value
})
// Create template & pass configuration object
$('<option></option>', {
id : i,
text : key,
value : value,
class : "selectS",
'data-meta' : metaData
}).appendTo('#mySelect');
});
}
});
}
$('#mySelect').change(function() {
// Get data('meta') keys
let index = $(this).find(':selected').data('meta').index;
let key = $(this).find(':selected').data('meta').key;
let value = $(this).find(':selected').data('meta').value;
$("#dataId").text(index);
$("#dataKey").text(key);
$("#dataValue").text(value);
// Using template literals
//console.log(`================\nID: ${index}\nKey: ${key}\nValue: ${value}\n================`);
});
showData();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Select a Person:</h3>
<hr>
<select id="mySelect">
</select>
<hr>
<div id="data">
Index:
<span id="dataId">N/A</span><br>
Key:
<span id="dataKey">N/A</span><br>
Value:
<span id="dataValue">N/A</span>
</div>

How to save values from option to one array cell in a loop

So I got a loop of processes. You can check it here.
So the point is my system can have different number of processes. And for each process there can be more than one studio. What I want to achieve is to save studios under one process into one array cell divided by coma. So later I could use this array and split studios to insert it to database.
My save function:
var LISTOBJ = {
saveList: function() {
$(".output").html("");
$(".studio").each(function() {
var listCSV = [];
$(this).find("input").each(function() {
listCSV.push($(this).text());
});
var values = '' + listCSV.join(',') + '';
$(".output").append("<input type='text' name='studio[]' value='" + values + "' />");
$("#output").append("<p>" + values + "</p>");
console.debug(listCSV);
});
}
}
But it seems it doesnt work. What do I need to change to achieve what i want? Thank you
on html file, on process 1 select option add this to the class attribute process-1, and on the process 2 also add process-2 on class attribute then, modify the saveList function
var processList = {process_1 : [] , process_2 : []};
$(".output").html("");
$(".studio").each(function() {
var text = $(this).val();
var process1 = $(this).hasClass('process-1');
var process2 = $(this).hasClass('process-2');
if(text) {
listCSV.push(text);
if(process1) {
processList.process_1.push(text);
} else if (process2) {
processList.process_2.push(text);
}
}
});
listObj.saveList = listCSV;
var values = listCSV.join(', ');
$(".output").append("<input type='text' name='studio[]' value='" + values + "' />");
$("#output").append("<p>" + values + "</p>");
console.log(processList);
ahh, i think i have solved the first question, about the question #1. on your html file add value attribute on each option. and also remove the div class="studio" hence put the class "studio" on the select class. after that try my code on the javascript file
// everytime the save button is clicked
$('#savebutton').click(function() {
saveList();
});
// set list studio
var listCSV = [];
// your list object
var listObj = {saveList: []};
// save list function
function saveList() {
$(".output").html("");
$(".studio").each(function() {
var text = $(this).val();
if(text) {
listCSV.push(text);
}
});
listObj.saveList = listCSV;
var values = listCSV.join(', ');
$(".output").append("<input type='text' name='studio[]' value='" + values + "' />");
$("#output").append("<p>" + values + "</p>");
}

Getting a 'Cannot find variable' error trying to access a json object

hopefully somebody can help me. The JS below, loads a JSON file and parses the counties into a select menu. It also removes duplicates. Now in the JSON feed, each item has something like this:
{
"County":"Antrim",
"Town":"Antrim Town",
"Restaurant":"Diane's Restaurant & Pizzeria"
}
What I am trying to do is in the first select menu, once the user chooses the county, the second select menu is updated with values from the son object. At the moment I'm getting a 'Cannot find variable' error and I can't work out why. Is the data array not available for some reason?
<script type="text/JavaScript">
$(document).ready(function(){
//get a reference to the select elements
var county = $('#county');
var town = $('#town');
var restaurant = $('#restaurant');
//request the JSON data and parse into the select element
$.getJSON('rai.json', function(data){
console.log(data);
//clear the current content of the select
$('#county').html('');
$('#county').append('<option>Please select county</option>');
$('#county').html('');
$('#town').append('<option>Please select town</option>');
$('#restaurant').html('');
$('#restaurant').append('<option>Please select restaurant</option>');
//iterate over the data and append a select option
$.each(data.irishtowns, function(key, val) {
county.append('<option id="' + val.County + '">' + val.County+ '</option>');
});
var a = new Array();
$('#county').children("option").each(function(x){
test = false;
b = a[x] = $(this).text();
for (i=0;i<a.length-1;i++){
if (b ==a[i]) test =true;
}
if (test) $(this).remove();
});
});
$( "#county" ).change(function() {
var myCounty = $(this).val();
console.log(myCounty);
$.each(data.irishtowns, function(key, val) {
if (val.Town === myCounty) {
town.append('<option id="' + val.Town + '">' + val.Town + '</option>');
}
});
});
});
</script>
Data is not in scope in this line
$.each(data.irishtowns, function(key, val) {
You could move this up into the callback, or use a global variable to provide access: i.e. in the callback have a line countries = data and then
$.each(countries.irishtowns, function(key, val) {

How to get Json as key and value in the Ajax $.getJSON()?

I have this ajax code for getting json from Jobs.json file.
$(document).ready(function(){
$('#btn2').click( callJobs );
});
function callJobs()
{
alert("getting results...");
$.getJSON('Jobs.json', function(JSON){
$('#result').empty();
$.each(JSON.jobs, function(i, JOB){
$('#result')
.append(JOB.Job +'<br />')
.append(JOB.Priority+'<br />')
.append(JOB.DueDate+'<br />')
.append(JOB.Iscompleted+'<hr />');
});
});
}
Jobs.json code is below.
{
"jobs":[
{
"Job":"Job1",
"Priority":"Low",
"DueDate":"11.03.2013",
"Iscompleted":"No"
},
{
"Job":"Job2",
"Priority":"High",
"DueDate":"11.03.2013",
"Iscompleted" : "No"
},
{
"Job":"Job3",
"Priority":"Medium",
"DueDate":"11.03.2013",
"Iscompleted":"No"
}
]
}
Now I want to rewrite $.each function dynamically.That is, it will write the json string as key and value instead of .append() .
This would walk over the properties of each job dynamically:
$.getJSON('Jobs.json', function(JSON){
var $container = $('#result').empty();
$.each(JSON.jobs, function(i, JOB) {
$.each(JOB, function(key, value) {
$container.append(key + ': ' + value + '<br />');
});
$container.append('<hr />');
}
});
Demo
Here's my approach. I've added comments to explain the process.
$.each(JSON.jobs, function(i, JOB) {
// an empty array for the output values
var values = [];
// iterator over each property in the current JOB object
for (var prop in JOB) {
// add an item to the array in format "key: value"
values.push(prop + ': ' + JOB[prop]);
}
// join the array values using '<br />' as separator;
// append to #result and add an '<hr />' after
$('#result').append(values.join('<br />')).append('<hr />');
});
My goals for this solution were to keep it readable (at the cost of an added array), select the #result element only once, and not have to deal with knowing whether to add that last <br /> during each loop. The other solutions append an extra <br /> after the last property and before the <hr /> whereas this and your original solution do not.

Javascript - Populating a form dynamically based on one object and filling in the values from another object

I have a JSON object that I use as a Template for all available Fields that can be added to an element in my Object that is used to Store the values.
I have another Object that holds values. The k,v of this Object storing all the values was not generated in my application. It is handed to me and I need to populate that value in a form that is created dynamically based on my JSON which defines all availabl keys for a given element. Its best I show you my demo app.
Demo: http://jsfiddle.net/bGxFC/15/
1. Click "Button_2" label - Notice how it populates a form with 5 k,v inputs
2.Now click "Button_1" label - Notice how this has 6 k,v inputs
3. Both of these are "Type": "Button" but "Button_2" is missing 'Transition' from its inputs
4This is where my 'var controls' object comes in. It defines all the available option that each type can have.
The Problem
I need to alter my code to use the values from 'objStr' and place them into a form that was created by 'controls'. And once I add a value to an empty input(i.e.The 'Transition' input in "Button_2") it will be saved back to 'objStr'.
Here is my code:
var controls = {
"Button":{"Type": "", "Transition": "","BackgroundImage": "","Position": "","Width": "","Height": ""},
"Image":{"Type": "","BackgroundImage": "","Position": "","Width": "","Height": ""},
"Label":{"Type": "","Position": "","Width": "","Height": "","Text": "","FontSize":"","Color": "", "FontType": ""}
};
objStr = {
"View_1":
{
"Image_1":{
"Type":"Image",
"BackgroundImage":"Image.gif",
"Position":[0,0],
"Width":320,
"Height":480
},
"Button_1":{
"Type":"Button",
"BackgroundImage":"Button.gif",
"Transition":"View2",
"Position":[49,80],
"Width":216,
"Height":71
},
"Button_2":{
"Type":"Button",
"BackgroundImage":"Button2.gif",
"Position":[65,217],
"Width":188,
"Height":134},
"Label_1":{
"Type":"Label",
"Position":[106,91],
"Width":96,
"Height":34,
"Text":"Button",
"FontSize":32,
"Color":[0.12549,0.298039,0.364706,1]
}
}
};
$(document).ready(function () {
var $objectList = $('<div id="main" />').appendTo($('#main'));
$.each(objStr.View_1, function(k, v) {
$('<div/>').append(k).appendTo($objectList).on('click', function(){
var $wrapper = $('#form .wrapper').empty();
if(typeof v === 'string') {
$('<div class="item" />').append('<span class="key">' + k + '</span>' + '<input value="' + v + '"/>').appendTo($wrapper);
}
else {//object
$('<h3 class="formHeading" />').append(k).appendTo($wrapper);
$.each(v, function(key, val) {
$('<div class="item" />').append('<span class="key">' + key + '</span>' + '<input value="' + val + '"/>').appendTo($wrapper);
});
}
$("<button>Save</button>").appendTo($wrapper).on('click', function() {
if(typeof v === 'string') {
v = $(this).closest(".wrapper").find("input").val();
}
else {//object
$(this).closest(".wrapper").find(".item").each(function(i, div) {
var $div = $(div),
key = $div.find(".key").text(),
val = $div.find("input").val();
v[key] = val;
});
}
});
});
});
});

Categories

Resources