i need to create drop
down list based on following json array,there will be 5 drop down list , if i select i need to populate other four for example if i select Hindi in first drop-down list then
Second list Third list Forth list Fifth list
"History", "Philosophy", "Political Science" "English"
"Sociology", "BLANK" "BLANK" "BLANK"
"Economics"
Now when i use jquery to implement this the list is not populating properly.I can not break down the inner array.
i am attaching link of jsfidle.Do i have to change the json format.
{
"Hindi": [
[
"History",
"Sociology",
"Economics"
],
"Philosophy",
"Political Science",
"English"
],
"Bengali": [
["History" ,"Sociology"
],
"Sanskrit",
"Philosophy",
"Political Science"
],
"English": [["History","Sociology","Economics"],
"Philosophy",
"Political Science",
["Bengali","Hindi"]
]
}
When parsing JSON assume that you have the same structure for every dropdown :
{"1select":[["2select values..."],[3select values..."],[4select values..."],[5select values..."]]}
(if there is no array -> create one)
and than do the same for every dropdown.
CODE :
var jsonObj = {"Hindi":[["History","Sociology","Economics"],"Philosophy","Political Science","English"],"Bengali":[["History","Sociology"],"Sanskrit","Philosophy","Political Science"],"English":[["History","Sociology","Economics"],"Philosophy","Political Science",["Bengali","Hindi"]]}
function updateSelect() {
var getOpts = function(raw){
var values = raw;
if (!(raw instanceof Array)){
values = [raw, ""];
}
var result = [];
values.forEach(function(obj){
result.push(new Option(obj, obj));
});
return result;
};
var newKey = $("#select1").val();
var mappings = [{"#select2":0},{"#select3":1},{"#select4":2},{"#select5":3}];
var selected = jsonObj[newKey];
mappings.forEach(function(mapping){
var selector = Object.keys(mapping)[0];
var index = mapping[selector];
$(selector).empty();
var opts = getOpts(selected[index]);
$(selector).append(opts);
});
}
$(document).ready(function() {
$("#select1").change(updateSelect);
updateSelect(); // For initial page load.
});
Example : here
Related
I have an array called category.
var category = ["automobile","Fashion","Music Instruments"]
and I need to link this array with the below array according to product.
var products = ["LandRover","Guitar","vintage,"Drums","Maserati","Piano"]
I think you are talking about some stuff like this?...
//variables predefined
var category = ["Automobile","Fashion","Music Instruments"]
var products = ["LandRover","Guitar","vintage","Drums","Maserati","Piano"]
//create a object categories where later we will add our products!
var categories = { };
//add values(category & products)
categories[ category[0] ] = [ products[0] , products[4] ]; //Automobile
categories[ category[1] ] = [ products[2] ]; //Fashion
categories[ category[2] ] = [ products[1] , products[3] ,products[5] ]; //Music Instrument
So now if you wanna display some value of 'automobile' for example, just:
//METHOD1
categories['automobile']
//METHOD2
categories[ category[0] ] //category[0]->automobile
And what you get is the array with all the products of category,so you just have to choose wich one you want.
Here you can see what you have got in console.
Function for show it in some HTML ( void html i hope)
function showObjectOnHTML( obj ){
for (var key in categories) { //check categories of thethe object
if (categories.hasOwnProperty(key)) {
var CATEGORIES = key;
var SPAN = document.createElement('SPAN');
SPAN.setAttribute('style','font-weight:bold; font-size: 20px; margin-left: 5px; display:block;');
SPAN.appendChild( document.createTextNode( CATEGORIES ) );
document.body.appendChild(SPAN);
var PRODUCTS = categories[key];
for( var i=0; i<PRODUCTS.length; i++){
var SPAN = document.createElement('SPAN');
SPAN.setAttribute('style','margin-left: 15px;font-size: 20px; display:block;');
SPAN.appendChild( document.createTextNode( PRODUCTS[i] ) );
document.body.appendChild(SPAN);
}
}
}
}
For show it,just type,:
showObjectOnHTML(categories);
I think what you need is an object (used like a "hashmap" in java):
//set examples
var category = {
automobile: [],
fashion: [],
musicInstuments: ["Piano"]
};
category["automobile"] = category["automobile"].concat(["LandRover", "Maserati"]);
category.fashion.push("Vintage");
//get examples
for(var key in category){
category[key].forEach(function(item){
console.log(item);
});
}
console.log(category.automobile[0]);
Using an object will also give you constant access time to the category you are looking for (instead of iterating over n items to find it)
Maybe if you use objects instead of only lists?
var categories = [
{
name: "Automobile",
products: ["LandRover", "Maserati"]
},
{
name: "Fashion",
products: ["Vintage"]
},
{
name: "Music Instruments",
products: ["Guitar", "Drums", "Piano"]
}
]
Also, like someone commented, what exactly do you want to accomplish?
EDIT
This JSFiddle shows one way to list products in each category using AngularJS.
If laptop model and serial id are same, i've to add new field totalModel and increase count. For example in below case: serialid "1" and laptop model "xyz" are coming two time so i want to add "totalModel" count as 2 and so on. How can i achieve this in jquery
This question is not really about jQuery, it is about mapping and filtering arrays and objects. However, we can use some jQuery convenience methods to solve it.
A large part of solving these problems is by properly defining what you want to do. It sounds from your question that you want to get a map of unique serial ids per laptop model type. We can use JavaScript's Array.prototype.reduce to produce just such a map (Note that we will take the 'sold' value for the first of each laptop model we encounter):
var laptop_models = data.reduce(function (memo, obj) {
if (!memo[obj.laptopModel]) {
memo[obj.laptopModel] = {
unique_serial_ids: [],
sold: obj.sold
};
}
if ($.inArray(obj.serialid, memo[obj.laptopModel].unique_serial_ids) === -1) {
memo[obj.laptopModel].unique_serial_ids.push(obj.serialid);
}
return memo;
}, {});
Next, we can map our laptop_models object into the array you specified as your expected result:
var result = $.map(laptop_models, function (laptop_model, model_name) {
return {
laptopModel: model_name,
totalModel: laptop_model.unique_serial_ids.length,
sold: laptop_model.sold
};
});
You got the idea already. Iterate through the array.
if them item is in a hash, increment the count, otherwise, add to the hash and set the count to 1
var hash = {};
for (var i = 0;i<data.length;i++) {
if (hash[data[i].laptopModel) {
hash[data[i].laptopModel]++;
}
else
hash[data[i].laptopModel] = 1;
}
var data = [
{
"serialid": 1,
"laptopModel": "xyz",
"sold": "yes",
"cnt": 5
},
{
"serialid" :1,
"laptopModel": "xyz",
"sold": "yes",
"cnt": 4
},
{
"serialid": 1,
"laptopModel": "abc",
"sold": "yes",
"cnt": 3
},
{
"serialid": 3,
"laptopModel": "xyz",
"sold": "yes",
"cnt": 2
}];
var result = []; //work if result = {};
var tempArray = []; // used to store unique name to prevent complex loop
data.forEach(function(item){
if($.inArray(item.laptopModel, tempArray)< 0){// unique name
result.push(formatData(item));
tempArray.push(item.laptopModel);
}
else{
var indexNew = $.inArray(item.laptopModel, tempArray);
result[indexNew]["totalModel"] += 1;
}
});
function formatData(item){
return{
"laptopModel": item.laptopModel,
"sold": item.sold,
"totalModel": 1
}
}
alert(JSON.stringify(result)); //expect array 2 item but it's empty array
console.log(result); //Will have result 2 item when I view console window
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
How would you go about getting all inventory locations for a particular item? What I would like is to check if a specific inventory location has any allotted inventory for an item.
I have tried to use the nlapiSearchRecord('item',null,filter,columns) to try this but it only returns the preferred location and not all locations even though their is inventory in the other locations.
Filters were setup as such:
filters = [ new nlobjSearchFilter('internalid',null,'is',10)];
If I add new nlobjSearchFilter('location',null,'is',34) to the filters which is the id for the inventory location I am looking for, I don't get any results at all.
the return I get from the above filters only list the preferred location and not any other locations with available inventory.
-- UPDATE --
After updating the code to use the suggestion below I am now getting the inventory location but not the correct inventory count for the location which should be 5 not 87
var itemId = 3376;
var locationId = 34;
var items = [];
var filters = [];
var columns = [];
filters = [
new nlobjSearchFilter('internalid',null,'is',itemId),
new nlobjSearchFilter('inventorylocation',null,'is',locationId),
new nlobjSearchFilter('quantityavailable',null,'greaterthan',0)
];
columns = [
new nlobjSearchColumn('itemid'),
new nlobjSearchColumn('inventorylocation'),
new nlobjSearchColumn('quantityavailable'),
new nlobjSearchColumn('quantityonhand'),
];
var results = nlapiSearchRecord('item',null,filters,columns);
if (results != null)
{
for (var i=0, l=results.length; i < l; i++)
{
var result = results[i];
items.push(result);
}
}
OUT PUT printed in JSON Format
{
"id": "3376",
"recordtype": "assemblyitem",
"columns": {
"itemid": "Marketing : Misc : T-Shirt Womens Medium",
"inventorylocation": {
"name": "InventoryLocation",
"internalid": "34"
},
"quantityavailable": 87,
"quantityonhand": 90
}
}
Thanks in advance.
I believe the field to use is the 'inventorylocation' field.
You should use the locationquantityavailable and locationquantityonhand columns instead of the ones you are using.
For references to the available columns/fields on a records, you may lookup the "Records Browser" in Help.
I'm still very new to array, my question is how do you links arrays one after another?
For example:
In the season array below, there are 4 keys/values, then in the designer0 and designer1 array, there are 3 keys/values pairs.
For designer0 array, it's belong to season[0] and for designer1 array, it's belong to season[1], but how do I write it in such a way that there are parent and child related?
var season = new Array();
season[0] = "summer 2013";
season[1] = "winter 2014";
season[2] = "autumn 1998";
season[3] = "spring 2005";
var designer0 = new Array();
designer[0] = "Albbs";
designer[1] = "Alexander Wang";
designer[2] = "BCBG Max Azria";
var designer1 = new Array();
designer[0] = "William Howe";
designer[1] = "Bringingthewood";
designer[2] = "Kesha";
You need a new type: "object", just like key & value.
var seasons = [{
name: "summer 2013",
designers: ["Albbs", "Alexander Wang", "BCBG Max Azria"]
}, {
name: "winter 2014",
designers: ["William Howe", "Bringingthewood", "Kesha"]
}];
object array.
If we are talking about javascript, you should remember: there are no native associative arrays in it. Since your season already contains data, the only way to maintain subordination is to create associative array, where season name will be a key and designers data - a value.
However, you can use array of objects to create desired data structure:
var seasons = [
{
"index" : 0,
"name" : 'summer 2013',
"designers": ['Albbs', 'Alexander Wang']
},
{
"index" : 1,
"name" : 'winter 2014',
"designers": ['William Howe', 'Kesha']
}
];
-see this fiddle to check how to work with such data.
You can use JSON:
[
{
"season":"summer 2013",
"designer1":"Albbs",
"designer2":"William Howe"
},
{
"season":"winter 2014",
"designer1":"Alexander Wang",
"designer2":"Bringingthewood"
}
]
Add a new array that links them and then refer to that array:
seasonal_designers =
[
0 = {designer0[0],designer0[1],designer0[2]}
1 = {designer1[0],designer1[1],designer1[2]}
]
Now get your stuff like this:
value=''
for(i in seasonal_designers[specify number])
value+=seasonal_designers[specify number][i] + ' (the designers id '+ i +')'
I have a value stored in array variable item like
var item = JSON.stringify(product);
cartproduct[cartproduct.length] = item;
item holds data such as
{
"Product": "1001",
"Brand": "Dell",
"Model": "Inspiron ",
"Price":"25000"
}
Now i want to display this item data in respective jqgrid columns like Product, Brand, Model ..
I saw one jsFiddle example like
http://jsfiddle.net/amorris/yNw3C/
Now all I want is my item value in the format of data.
var data = [[48803, "DSK1", "", "02200220", "OPEN"]];
var item = [[1000,"Sony","Vaio",40000]];
Try this:
var itemFormatted = [[
item.Product,
item.Brand,
item.Model,
item.Price
]];
// Now itemFormatted will be in the correct format
Check out Working with Javascript objects for more information.