multidimensional json data into different input text boxes through jquery/ajax - javascript

I have created an autocomplete searchbox followed by two input text boxes.
Please help me how to assign values of autocomplete's selected values.
For ex. if we select ajax, corresponding price should be assigned to 1003 and role should be assigned to foreign.
My json response which I got from php echo output is :
{
"users": [
{
"name": "ajax",
"price": "1003",
"author": "foriegn"
},
{
"name": "jquery",
"price": "1000",
"author": "dd"
},
{
"name": "mysql",
"price": "1000",
"author": "f"
},
{
"name": "php",
"price": "1000",
"author": "abc"
},
{
"name": "php frameword",
"price": "1000",
"author": "def"
},
{
"name": "php tutorial",
"price": "1000",
"author": "ghi"
},
{
"name": "wordpress",
"price": "1000",
"author": "g"
},
{
"name": "wordpress theme",
"price": "1000",
"author": "h"
},
{
"name": "xml",
"price": "1000",
"author": "j"
}
]
}
My JavaScript code below :
var counter = 2;
var availableTags = ["php", "php frameword", "php tutorial", "jquery", "ajax", "mysql", "wordpress", "wordpress theme", "xml"];
$("#addButton").click(function () {
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
var roleInput = $('<input/>', {
type: 'text',
placeholder: 'Role',
name: 'Role' + counter,
id: 'textbox' + counter
});
var priceInput = $('<input/>', {
type: 'text',
placeholder: 'price',
name: 'price' + counter,
id: 'textbox' + counter
});
var searchInput = $('<input/>', {
type: 'text',
placeholder: 'search',
name: 'search' + counter,
id: 'se' + counter
});
var hidd = $('<input/>', {
type: 'hidden',
name: 'searchhid' + counter,
id: 'searchhid' + counter
});
newTextBoxDiv.append(searchInput).append(roleInput).append(priceInput).append(hidd);
newTextBoxDiv.appendTo("#TextBoxesGroup");
$('#se' + counter).autocomplete({
source: availableTags
});
counter++;
});
Current fiddle setup is at : http://jsfiddle.net/premgowda/UC74L/6/
PS: I am extremely new to Json and jquery. I havent added the json output into my fiddle setup as I am not sure how to do it .

Use jQuery UI autocomlete select event:
http://api.jqueryui.com/autocomplete/#event-select
Once you've got the selected value, find the matching object and select it's others properties. Like this:
for(i = 0; i < users.length; ++i) {
(users[i].name == selected) {
break;
}
}
price = users[i].price;
author = users[i].author;

Related

Can't seem to reference data in a complex JSON file, probably just my syntax

I am a noob so please forgive me. I have the following JSON file:
`{ "Series": {"Next":
[ { "Name": "Cheese", "Price" : 2.50, "Location": "Refrigerated foods"},
{ "Name": "Crisps", "Price" : 3, "Location": "the Snack isle"},
{ "Name": "Pizza", "Price" : 4, "Location": "Refrigerated foods"},
{ "Name": "Chocolate", "Price" : 1.50, "Location": "the Snack isle"},
{ "Name": "Self-raising flour", "Price" : 1.50, "Location": "Home baking"},
{ "Name": "Ground almonds", "Price" : 3, "Location": "Home baking"} ]}`
I'm trying to reference the Name, Location and Price but it's now working. Here is the JavaScript code I am using:
.then(function(json) {
for(var i = 0; i < json.Next.length; i++) {
var listItem = document.createElement('li_prod');
listItem.innerHTML = '<strong_prod>' + json.Next[i].Name + '</strong_prod>';
listItem.innerHTML +=' can be found in ' + json.Next[i].Location + '.';
listItem.innerHTML +=' Cost: <strong_prod>£' + json.Next[i].Price + '</strong_prod>';
myList.appendChild(listItem);
}
that code is not picking up the Name, Location or price. How can I reference the data? Something like json.Series.Next[i].Name?
with the structure of your object it's more json.Series.Next instead of json.Next
var json = {
"Series": {
"Next":
[{
"Name": "Cheese",
"Price": 2.50,
"Location": "Refrigerated foods"
},
{
"Name": "Crisps",
"Price": 3,
"Location": "the Snack isle"
},
{
"Name": "Pizza",
"Price": 4,
"Location": "Refrigerated foods"
},
{
"Name": "Chocolate",
"Price": 1.50,
"Location": "the Snack isle"
},
{
"Name": "Self-raising flour",
"Price": 1.50,
"Location": "Home baking"
},
{
"Name": "Ground almonds",
"Price": 3,
"Location": "Home baking"
}
]
}
}
var myList = document.getElementById('my-list');
for (var i = 0; i < json.Series.Next.length; i++) {
var listItem = document.createElement('li_prod');
listItem.innerHTML = '<strong_prod>' + json.Series.Next[i].Name + '</strong_prod>';
listItem.innerHTML += ' can be found in ' + json.Series.Next[i].Location + '.';
listItem.innerHTML += ' Cost: <strong_prod>£' + json.Series.Next[i].Price + '</strong_prod>';
myList.appendChild(listItem);
}
<div id="my-list">
</div>

Grouping array nested value while comparing 2 objects

I am working in small react project & I am facing issue in grouping the data. Requirement is to group the id & its feature into a single row if same id is there in before & after object.
Json Data:
{
"before":{
"device": [
{
id:"1234",
price:"10,
features:[
{name:"samsung",price:"10"},
{name:"Apple",price:"20"}
]
},
{id:"2154",
price:"20,
features:[
{name:"samsung",price:"30"},
{name:"Moto",price:"40"}
]
]
},
"after":{
"device": [
{
id:"1234",
price:"50,
features:[
{name:"samsung",price:"20"},
{name:"Lenovo",price:"30"}
]
},
{id:"2158",
price:"40,
features:[
{name:"samsung",price:"30"}
]
]
}
}
Expected grouping to be shown in UI is shared in image.
I tried to get unique ids in one array and lopping through after array and comparing unique array id I am getting unique id to show but issue i am facing while grouping their related feature.
Can anyone please help me to get a best approach to handle this requirement.
Thanks
There are 3 things i'd suggest you:
1.) Please verify the data your'e posting is correct and in proper format, people won't be able to help if the data is incorrect.
2.) The UI display requirement should be simple enough.
Now, if you still want to achieve this requirement i believe the correct JSON and the merged output json will look something like below:
//Correct input data that you have:
var input = {
"before": {
"device": [
{
"id": "1234",
"price": "10",
"features": [
{
"name": "samsung",
"price": "10"
},
{
"name": "Apple",
"price": "20"
}
]
},
{
"id": "2154",
"price": "20",
"features": [
{
"name": "samsung",
"price": "30"
},
{
"name": "Moto",
"price": "40"
}
]
}
]
},
"after": {
"device": [
{
"id": "1234",
"price": "50",
"features": [
{
"name": "samsung",
"price": "20"
},
{
"name": "Lenovo",
"price": "30"
}
]
},
{
"id": "2158",
"price": "40",
"features": [
{
"name": "samsung",
"price": "30"
}
]
}
]
}
};
// Output JSON which you should need to show the desired output.
var output = {
"devices": [
{
"id": 1234,
"feature": [
{
"name": "1234",
"price": {
"before": 10,
"after": 50
}
},
{
"name": "samsung",
"price": {
"before": 10,
"after": 20
}
},
{
"name": "apple",
"price": {
"before": 10,
"after": 0
}
},
{
"name": "lenovo",
"price": {
"before": 0,
"after": 30
}
}
]
}
]
};
3.) Please try to get the desired output from input yourself as this will help you learn a lot of things in between, as suggested by some please use map, filter, forEach for your requirement.
Hope this helps. Thanks!
You could take a nested approach for grouping.
var data = { before: { device: [{ id: "1234", price: "10", features: [{ name: "samsung", price: "10" }, { name: "Apple", price: "20" }] }, { id: "2154", price: "20", features: [{ name: "samsung", price: "30" }, { name: "Moto", price: "40" }] }] }, after: { device: [{ id: "1234", price: "50", features: [{ name: "samsung", price: "20" }, { name: "Lenovo", price: "30" }] }, { id: "2158", price: "40", features: [{ name: "samsung", price: "30" }] }] } },
cols = Object.fromEntries(Object.keys(data).map(k => [k, 0])),
result = Object.values(Object.entries(data).reduce((r, [col, { device }]) => {
device.forEach(({ id, price, features }) => {
r[id] = r[id] || [{ id, ...cols }];
r[id][0][col] = price;
features.forEach(({ name, price }) => {
let temp = r[id].find(q => q.name === name);
if (!temp) r[id].push(temp = { name, ...cols });
temp[col] = price;
});
});
return r;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use lodash library for grouping
https://lodash.com/docs/3.10.1#groupBy
Comparing 2 objects, and output equivalent values
var has = {"before":[{
name: 'Nokia',
os: 'Andriod',
features: {
camera: "200 MPixel Camera",
battery: "24 hours battery backup",
}
}],
"after":[{
name: 'Samsung',
os: 'Andriod',
features: {
camera: "200 MPixel Camera",
battery: "30 hours battery backup",
}
}]
};
function compare(Pro1, Pro2) {
var Val1 = Object.values(Pro1);
var Val2 = Object.values(Pro2);
var equivalent = [];
var keys = Object.keys(Pro1);
keys.forEach(k => {
if (Pro1.hasOwnProperty(k) && Pro2.hasOwnProperty(k)) {
if (typeof Pro1[k] === 'object') {
let recursiveResult = compare(Pro1[k], Pro2[k]);
equivalent.push(...recursiveResult);
} else if (Pro1[k] === Pro2[k]) {
equivalent.push(Pro1[k]);
}
}
});
return equivalent;
}
let equiv = compare(has["before"], has["after"]);
console.log(equiv);

How to append an input inside each div that created from Json

i have a json and i create a simple dynamic form based on my json file . there are labels and each lables are exist in divs seperately.but there is a problem in this code that this code does not show my inputs. how to appends them inside each divs below each lable?
this code should show input but does not work.
here is my code :
document.body.onload = addElement;
function addElement() {
var schema = [{
"queestion": "Name",
"type": "128",
"attrs": [{
"attr": {
"name": "class",
"value": "nofilling2 engword"
}
},
{
"attr": {
"name": "id",
"value": "name"
}
},
{
"attr": {
"name": "type",
"value": "text"
}
},
{
"attr": {
"name": "placeholder",
"value": "Name"
}
},
{
"attr": {
"name": "name",
"value": "_root.passengerinfo__1.passengerinfo.fullname.firstname"
}
}
]
},
{
"queestion": "Family",
"type": "128",
"attrs": [{
"attr": {
"name": "class",
"value": "nofilling2 engword"
}
},
{
"attr": {
"name": "id",
"value": "family"
}
},
{
"attr": {
"name": "type",
"value": "text"
}
},
{
"attr": {
"name": "placeholder",
"value": "Family"
}
},
{
"attr": {
"name": "name",
"value": "_root.passengerinfo__1.passengerinfo.fullname.lastname"
}
}
]
}
]
for (var i = 0; i < schema.length; i++) {
var type = schema[i].type;
if (type == 128) {
var titleinput = schema[i].queestion;
var newDiv = document.createElement("div");
newDiv.className = 'c-infoo';
var newContent = document.createElement('label');
newContent.className = 'abs-tlt';
newDiv.appendChild(newContent);
newContent.innerHTML = titleinput + " : ";
document.getElementById('tblreserve').appendChild(newDiv);
var string = "<input ";
for (var y = 0; y < schema[i].attrs.length; y++) {
string += schema[i].attrs[y].attr.name + '="' + schema[i].attrs[y].attr.value + '" '
}
string += ">";
newDiv.appendChild = string;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="tblreserve"></div>
In your last line you wrote newDiv.appendChild=string;.
But stringas its name says is a String and can't be appended as an child.
You can use your string by writing newDiv.innerHTML+=string; instead.
PS: Please fix your indentation style. It doesn't look very nice...

Create JSON object with same keys for API call

I'm trying to create a JSON object for an API call which has the following format:
....
"Key": "Value",
"Package": {
"Dimensions": {
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Length": "20",
"Width": "25",
"Height": "30"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "80"
}
},
"Package": {
"Dimensions": {
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Length": "15",
"Width": "24",
"Height": "27"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "50"
}
},
"Key": "Value",
....
I should add as many "Package" objects as needed. However, I've tried doing this in many different ways but every time that I parse the variable to be used the first objects get overwritten and I end up with only the last object.
This is what I'm trying at the moment, still with no luck:
var lineItems = '{';
for (var i=0;i<inputObject.packages.length;i++) {
lineItems += '"Package": {"PackagingType": {"Code": "02","Description": "Rate"},"Dimensions": {"UnitOfMeasurement": {"Code": "IN","Description": "inches"},"Length": ' + inputObject.packages[i][0].toString() + ',"Width": ' + inputObject.packages[i][1].toString() + ',"Height": ' + inputObject.packages[i][2].toString() + '},"PackageWeight": {"UnitOfMeasurement": {"Code": "Lbs","Description": "pounds"},"Weight": ' + inputObject.packages[i][3].toString() + '}}';
if (i !== inputObject.packages.length-1) {
lineItems += ',';
}
}
lineItems += '}';
lineItems = JSON.parse(lineItems);
How about numbering your packages, ie:
for (var i=0;i<inputObject.packages.length;i++) {
lineItems+='"Package" + i : { ... }'
}
edit: to get required result (as an array - because it's not JSON), here's an example:
var a=[];
var b={"package": {"c":100,"d":200,"e":300}}
var c={"package": {"c":800,"d":700,"e":600}}
a.push(b);
a.push(c);
console.log(a);

JS string counter

I want this code to count the number of times that category and message are in the bottom string, regardles of the different id number. The code just gives me the last one.
It is quite messy, sry. Thanks for your help.
Kind regards.
counter = function() {
var value = $('#text').val();
if (value.length == 0) {
$('#wordCount').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
};
$(document).ready(function() {
var obj = {"data" : {
"from": {
"category": "cat1",
"id": 1,
"message": "WIZ1"
},
"from": {
"category": "cat2",
"id": 2,
"message": "WIZ2"
},
"from": {
"category": "cat3",
"id": 3,
"message": "WIZ3"
},
"from": {
"category": "cat4",
"id": 4,
"message": "WIZ3"
},
}
};
$.each(obj, function() {
$.each(this, function(name, value) {
$("#result").append(name + '=' + value.category);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result">Words: <span id="wordCount">0</span>
<br/>
</div>
You have a single object with the "from" property being overwritten 4 times. It looks like what you wanted was to instead have an array, like the example below.
I also changed the code to actually capture the categories and messages, like the description in your post, after the loops those objects will have the count by message and count by category.
counter = function() {
var value = $('#text').val();
if (value.length == 0) {
$('#wordCount').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
};
$(document).ready(function() {
var obj = {"data" : [
{
"category": "cat1",
"id": 1,
"message": "WIZ1"
},
{
"category": "cat2",
"id": 2,
"message": "WIZ2"
},
{
"category": "cat3",
"id": 3,
"message": "WIZ3"
},
{
"category": "cat4",
"id": 4,
"message": "WIZ3"
},
]
};
var categories = {};
var messages = {}
$.each(obj, function() {
$.each(this, function(name, value) {
if (!categories[value.category]) categories[value.category] = 0;
categories[value.category] += 1;
if (!messages[value.message]) messages[value.message] = 0;
messages[value.message] += 1;
$("#result").append(name + '=' + value.category);
});
});
console.log(categories);
console.log(messages);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result">Words: <span id="wordCount">0</span>
<br/>
</div>
Each of the items in the JS object have the same key ('from').
That's causing each one to overwrite the previous, which is why it's only finding the last one.
{
"data": {
"from1": {
"category": "cat1",
"id": 1,
"message": "WIZ1"
},
"from2": {
"category": "cat2",
"id": 2,
"message": "WIZ2"
},
"from3": {
"category": "cat3",
"id": 3,
"message": "WIZ3"
},
"from4": {
"category": "cat4",
"id": 4,
"message": "WIZ3"
}
}
}
This will allow it to iterate through each item as there will now be four items present.

Categories