I have SQLite table with columns id and name. I return array of those rows like json from autocomplete.php page. How to fill select with options ( drop down list ) with this json using jquery and JavaScript ? I am new to JavaScript and JQuery, I googled but didn't find how. In ASP.NET this is easy but here I don't know. Would somebody help ?
This is example of my JSON, can be much longer.
[
{
"id": "1",
"name": "test"
},
{
"id": "1",
"name": "test"
}
]
HTML:
<select id="sel">
</select>
JavaScript:
$(function() {
var data = [
{
"id": "1",
"name": "test1"},
{
"id": "2",
"name": "test2"}
];
$.each(data, function(i, option) {
$('#sel').append($('<option/>').attr("value", option.id).text(option.name));
});
})
Here's a working example. http://jsfiddle.net/ms2Ma/
Try this, This will give you an option to have any number of dropdown boxes and JSON nodes to configure dropdown boxes.
You need to follow few steps:
Create an array of dropdown boxes.(e.g. if you have to configure a phone then you should be using dropdown of color, memory etc.)
Create a JSON object as it is created in code. Dont change the configurable items name which starts with "level1" and end with any number of nodes, As it has to be sync with the index of items of array you are creating in the first place.
Here is the data:
var Dropdowns = ["Model", "Color", "Memory","design","covers","music"];
var Data ={"phones":[
{
"oid":":000000F0:00000458:",
"level1":"3G",
"level2":"white",
"level3":"16GB",
"level4":"slim",
"level5":"Back cover",
"level6":"headphone",
"price":"£568.63",
"addToCart":"#Cart1"
},
{
"oid":":000000F0:000003DA:",
"level1":"3G",
"level2":"black",
"level3":"16GB",
"level4":"slim",
"level5":"Flip cover",
"level6":"headphone",
"price":"£615.79",
"addToCart":"#Cart7"
}]};
See the full working code here:
https://jsfiddle.net/raju_sumit/681ppgq0/5/
Try this :)
Javascript:
$.getJSON("/array.json",
function (json) {
$.each(json,
function (key, value) {
$("#id-select").append("<option value='" + value.c + "'>" + value.d + "</option>");
});
});
A pure Javascript solution: this snippet shows how to populate a dropdown select from JSON data (using id as value and name as text.
The code creates a new Option object for each item in the JSON data and appends it to the select element with appendChild(). map is used in place of a for loop.
let data = [{
"id": "1",
"name": "name_1"
},
{
"id": "2",
"name": "name_2"
}
];
var selectElement = document.getElementById('mySelect');
data.map(item => mySelect.appendChild(new Option(item.name, item.id)).cloneNode(true));
<select id="mySelect" onchange="alert(this.value)"></select>
Related
I have JSON file with this structure:
{
"launches": [{
"name": "First Name"
}],
"launches": [{
"name": "Second Name"
}],
"launches": [{
"name": "Third Name"
}],
"launches": [{
"name": "Fourth Name"
}]
}
I add the data like this:
$('#div-name').append(d.name);
When this is displayed on a webpage, it is placed in one div with no spaces. I can add a <p> tag to the append, but that still displays ALL the data and creates new divs to display it.
Basically, what I am trying to do is to create a div for each separate "name" value and display only one value per div.
First of all, your "json" is not a valid json, remmeber that in a json object, you can not have duplicated keys. You can easily use an online validator to help you with that... and after you fix it, let's assume that what you actually have is an array of objects like:
[
{"name": "Falcon 9"},
{"name": "Orion"},
{"name": "PSLV"},
{"name": "Soyuz"}
]
with this valid json, you can easily loop trough all the elements like (and take that you are using jQuery):
var json = [ ... ];
$(function() {
$.each(json, function(i, item){
$("p").append("<div>" + item.name + "</div>");
});
});
here's a live test: https://jsbin.com/bixadegeye/1/edit?html,css,js,output
A slightly different way of going about it:
var data = {
"names": [
"Falcon 9",
"Orion",
"PSLV",
"Soyuz"
]
};
$.each( data["names"], function( key, value ) {
$('#div-name').append(value+"<br />");
});
Hi I'm currently creating an application to gather data form a website, and as I've researched you can used Json for that, now I have created a script to gather data, at first i have no problem with it, but when I cam across with a multi tree json i started having trouble.
here is my Json
{
"orders": [
{
"line_items": [
{
"id": 7660469767,
"name": "Personalised design - purple",
"properties": [
{
"name": "personalised text 1",
"value": "2"
},
{
"name": "personalised text 2",
"value": "Nuri &"
},
{
"name": "personalised text 3",
"value": "Samira"
}
],
}
]
}
]
}
I need to get the order.line_items.properties.value.
I tried this code but it says it does not work.
$.getJSON(order.json, function (data) {
$.each(data.orders.line_items.properties, function (index, value) {
$.each(this.value, function () {
console.log(this.text);
});
});
});
Can someone help me?
$.each(data.orders[0].line_items[0].properties, function (index, value) {
console.log(value.value);
});
Both orders and line_items are array, so it should have an access to array index first before accessing other object. And you don't have to use extra each in your code. The value above is an object for each properties. You can retrieve value there.
I have JSON data and that JSON data has parent child relation . I Want to create tree structure from it. i found many plugins and libraries but i can't found my requirement . I am getting this JSON data using PHP script.
Here is image that has tree structure that i want to create . i'm stuck at it.I know JSON is not as displayed in image but i only want to show you what a tree should look like .How to create tree like in image.All i want is javascript code to handle and create this type of structure of tree . Working example is must & much appreciated.
You can use JSON format as you like and tree should be collapsible.Also provide required JSON format for it.
and my JSON data as follows :
{
"2":
{
"5": "Wrist Watch"
},
"5":
{
"9": "Men's"
},
"18":
{
"3": "Clothing"
},
"28":
{
"1": "Perfumes"
},
"29":
{
"7": "Laptop",
"10": "Tablets"
},
"30":
{
"8": "Mobile"
},
"31":
{
"2": "Books"
},
"33":
{
"6": "Electronics"
},
"34":
{
"4": "Home & Kitchen\n"
}
}
If you want to roll your own, the keyword in "trees" is recursion. It needs to support any depth of data and the code and data should both support recursion.
This means your JSON data should be a recursive structure, where each node looks the same (and looks something like this):
{
id: 1, // data id
title: "title", // display title
children: [ // list of children, each with this same structure
// list of child nodes
]
}
Note: I have changed the sample data to contain more depth as 2 levels never shows up recursion problems.
e.g.:
{
id: 0,
title: "root - not displayed",
children: [{
id: 1,
title: "Option 1",
children: [{
id: 11,
title: "Option 11",
children: [{
id: 111,
title: "Option 111"
}, {
id: 112,
title: "Option 112"
}]
}, {
id: 12,
title: "Option 12"
}]
}, {
id: 2,
title: "Option 2",
children: [{
id: 21,
title: "Option 21"
}, {
id: 22,
title: "Option 22"
}]
}, {
id: 3,
title: "Option 3",
children: [{
id: 31,
title: "Option 31"
}, {
id: 32,
title: "Option 32"
}]
}]
}
The recursive function looks like this:
function addItem(parentUL, branch) {
for (var key in branch.children) {
var item = branch.children[key];
$item = $('<li>', {
id: "item" + item.id
});
$item.append($('<input>', {
type: "checkbox",
name: "item" + item.id
}));
$item.append($('<label>', {
for: "item" + item.id,
text: item.title
}));
parentUL.append($item);
if (item.children) {
var $ul = $('<ul>').appendTo($item);
addItem($ul, item);
}
}
}
JSFiddle: http://jsfiddle.net/0s0p3716/188/
The code recurses the structure, adding new ULs and LIs (with checkbox etc ) as it goes. The top level call just provides the initial root starting points of both the display and the data.
addItem($('#root'), data);
The end result looks like this:
If you want to toggle visibility, based on the checked state, use this:
$(':checkbox').change(function () {
$(this).closest('li').children('ul').slideToggle();
});
If you also want the labels to toggle the checkboxes, use this:
$('label').click(function(){
$(this).closest('li').find(':checkbox').trigger('click');
});
Note: I have only provided the most basic of styling as that will typically be "to taste". Examples in links were shown in another answer.
-- updated:
amended: possible wrong ids for items 31 & 32?
function for better selection and deselection(for parents cascading into child nodes):
$(function () {
addItem($('#root'), data);
$(':checkbox').click(function () {
$(this).find(':checkbox').trigger('click');
var matchingId = $(this).attr('id');
if ($(this).attr('checked'))
{
$('input[id*=' + matchingId +']').each(function() {
$(this).removeAttr('checked');
$(this).prop('checked', $(this).attr('checked'));
});
}
else {
$('input[id*=' + matchingId +']').each(function() {
$(this).attr('checked', 'checked');
$(this).prop('checked', $(this).attr('checked'));
});
}
});
$('label').click(function(){
$(this).closest('li').children('ul').slideToggle();
});
-- Update the fiddle with this as shown here(JsFiddle) and it will work better and also will allow you to click the text to expand without selecting at the same time - I know I find this far more useful. It will help (and this is personal preference) you to see what values and options are available without having to select the first.
The thing with programming is: existing libraries and tools rarely do exactly what you need. It's always up to you to convert the input data into exactly the format they expect and then the output data into the format you need. Occasionally this conversion requires more effort than writing your own code instead of a library function - this seems to be one of those occasions.
As #philosophocat already noted, the best way to present such a tree in HTML markup would be nested lists. All you need is iterate through the JSON data recursively and create the corresponding elements:
function createList(data)
{
var result = document.createElement("ul");
for (var key in data)
{
if (!data.hasOwnProperty(key) || key == "_title")
continue;
var value = data[key];
var item = createItem(key, typeof value == "string" ? value : value._title);
if (typeof value == "object")
item.appendChild(createList(value));
result.appendChild(item);
}
return result;
}
function createItem(value, title)
{
var result = document.createElement("li");
var checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
checkbox.setAttribute("name", "selection");
checkbox.setAttribute("value", value);
result.appendChild(checkbox);
result.appendChild(document.createTextNode(title));
return result;
}
document.body.appendChild(createList(jsonData));
Note that the order in which the items appear is "random" here, as object keys are generally unordered. You can change the code above to sort the keys somehow, or you can change the data to use arrays and define an order. I also added a "_title" property to the data to make sure the categories are labeled - your data doesn't have any labels at all for the categories.
Now you need to style the lists in such a way that they look like a tree. The obvious solution is using the list-style-image CSS property to replace the usual bullet points by a grid lines image. However, that doesn't work for nested lists - there you need to show multiple images, vertical lines from the higher-level lists as well as the image actually belonging to the current list item.
This can be solved by using background images for the list items instead, these background images will be shown next to sublists as well then. Here are the example styles I've got:
ul
{
padding: 0;
list-style-type: none;
font-size: 14px;
}
li
{
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAABkCAYAAABdELruAAAAP0lEQVR42u3PQQoAIAgEQP3/o6t7JAhdolkQD4sMZuwZazKKlGXniHRDOu6HfyKRSCQSiUQikUgkEolEIv0rTc/fNmQ78+lPAAAAAElFTkSuQmCC);
background-repeat: no-repeat;
padding-left: 13px;
}
li:last-child
{
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAJCAYAAADpeqZqAAAAHUlEQVR42mNkwAT/gZiRAQ/AK0mKplGbqGETThoACFgJCVdBEqAAAAAASUVORK5CYII=);
}
li > ul
{
margin-left: 5px;
}
Note that this will still get ugly if the sublist is too high - the height of the background image I used is merely 100px. This can be solved by using a larger background image of course. A cleaner alternative would be using border-image-slice CSS property but that one is currently only supported in Firefox.
Fiddle for this code
Edit: This article goes into more detail on styling nested lists like a tree. While the approach is similar, it manages to avoid the image size issues I mentioned above by using a separate image for the vertical line which can be repeated vertically. On the downside, that approach looks like it might only work with solid lines and produce artifacts if applied to dotted lines.
Use http://www.jstree.com/. This library provides each function I ever need when working with trees and javascript.
You simple have to change your json-response according to the given format (http://www.jstree.com/docs/json/):
{
id : "string" // will be autogenerated if omitted
text : "string" // node text
icon : "string" // string for custom
state : {
opened : boolean // is the node open
disabled : boolean // is the node disabled
selected : boolean // is the node selected
},
children : [] // array of strings or objects
li_attr : {} // attributes for the generated LI node
a_attr : {} // attributes for the generated A node
}
Set up the javascript and include all required files and there you go.
I just skip repeating the documentation by referring to it: http://www.jstree.com/
I'm using DynaTree for an internal site at work and it works fantastic.
Download DynaTree
Format your JSON as such (taking your screenshot as an example):
{
"title": "Sports & Outdoors",
"isFolder": true,
"key": "0",
"children": [
{
"title": "Fitness Accessories",
"key": "1",
"isFolder": true,
"children": [
{
"title": "Fitness Accessories",
"key": "2",
"isFolder": true,
"children": [
{
"title": "Pedometer & Watches",
"key": "3"
}
]
}
]
}
]
}
Run this JS on page load:
$("#buildTree").dynatree({
onActivate: function (node) {
// A DynaTreeNode object is passed to the activation handler
// Note: we also get this event, if persistence is on, and the page is reloaded.
leftActiveNodeKey = node.data.key;
},
persist: false,
checkbox: true,
selectMode: 3,
children: $.parseJSON(response.d)
});
To get the selected nodes you can use:
var selectedNodes = $("#buildTree").dynatree("getTree").getSelectedNodes();
Dynatree is pretty customization, both in look and function. Read through the documentation for the settings you need.
Check these sites.Hope this helps.
http://www.jstree.com/docs/json/
http://www.jeasyui.com/documentation/tree.php
http://jqwidgets.com/jquery-widgets-demo/demos/jqxtree/index.htm#demos/jqxtree/checkboxes.htm
#Gone Coding's example is excellent, but the child check boxes will not show as 'uncheked' even though the checked attribute is removed, as rendered in Chrome.
If you add,
$(this).prop('checked', false);
to the code, so it reads as
$(function () {
addItem($('#root'), data);
$(':checkbox').click(function () {
var matchingId = $(this).attr('id');
if ($(this).attr('checked'))
{
$('input[id*=' + matchingId +']').each(function() {
$(this).removeAttr('checked');
$(this).prop('checked', false);
$(this).prop('checked', $(this).attr('checked'));
return;
});
}
else {
$('input[id*=' + matchingId +']').each(function() {
$(this).attr('checked', 'checked');
$(this).prop('checked', $(this).attr('checked'));
});
}
});
$('label').click(function(){
$(this).closest('li').children('ul').slideToggle();
});
});
the child check boxes will fill or clear when the user makes a change.
I'm trying to build a nested array in jQuery based on a user's selection from a drop down menu. This will be used in a JSON request at a later date.
So far my code does produce (almost) the required result, however no matter order i select the options from my drop down menu, the output (which i log in the console at the end) is always the same.
$('#comboGenre').change(function () {
var values = $('#comboGenre').val();
var parsedJSON = JSON.parse($data); //Data returned from ajax request
for (var i = 0; i < values.length; i += 1) {
$genreList = parsedJSON.genre[i];
console.log($genreList);
}
});
So if i select RPG and Action from my drop down, the output gives me RPG and Driving. If i selected RPG, Driving and Action (in that order), i get what i would expect RPG, Driving and Action.
So it's just iterating through my JSON, when really it should be returning the 'selected' option.
How can i achieve this?
My JSON looks like this if it's useful:
{"genres": [{
"genre": "RPG",
"publishers": [{
"publisher": "Square",
"games": [{
"game": "FFX",
"rating": [
12, 15
]
}]
}]
},
{
"genre": "Driving",
"publishers": [{
"publisher": "Turn10",
"games": [{
"game": "Forza",
"rating": [
5
]
}]
}]
},
{
"genre": "Action",
"publishers": [{
"publisher": "EA",
"games": [{
"game": "COD",
"rating": [
18, 20
]
}]
}]
}
]}
EDIT:
I've also tried this:
$('#comboGenre').change(function () {
var parsedJSON = JSON.parse($data);
$genreList = "";
$.each(parsedJSON.genres, function(index, value){
$genreList = parsedJSON.genres[index];
console.log($genreList);
});
});
And i end up getting ALL the objects in my JSON, so from here, i'm only wanting to add the selected object to the $genreList variable.
If you broke out some of the logic and created a genre finding function and used the selected string to find the proper object you could then put the object into the variable you will use later. I do some checking to ensure that the genre that has been selected isn't already in my array which is because I am using the multiple select
JSFiddle: http://jsfiddle.net/vkTFq/
Code:
$(function(){
var selectedGenres = [];
var genres =[{"genre":"RPG","publishers":[{"publisher":"Square","games":[{"game":"FFX","rating":[12,15]}]}]},{"genre":"Driving","publishers":[{"publisher":"Turn10","games":[{"game":"Forza","rating":[5]}]}]},{"genre":"Action","publishers":[{"publisher":"EA","games":[{"game":"COD","rating":[18,20]}]}]}]
$('#comboGenre').change(function() {
$(this).find(":selected").each(function() {
var selectedGenre = findGenre($(this).val())
if (!genreAlreadySelected(selectedGenre.genre)) {
selectedGenres.push(selectedGenre);
};
});
console.log (JSON.stringify(selectedGenres));
});
function genreAlreadySelected(genre){
for(var i = 0; i < selectedGenres.length; i++){
if (genre == selectedGenres[i].genre) {
return true;
};
return false;
}
}
function findGenre(genre){
for(var i = 0; i < genres.length; i ++){
console.log(genre)
if(genre == genres[i].genre){
return genres[i];
}
}
};
});
I have a JSON being returned an I want to take the last 8 elements of the JSON and make a table. The table builds the way I expect it to but I'm getting undefined as the result value.
Here is the code for the getJSON, an edited down return and the table.
$.getJSON("loadloads.php", function(data){
[{
"value": {
"lineNumber": "258640",
"TypeId": "1",
"StopNumber": "1",
"ReferenceNo": "0002325063",
"LocationId": "3",
"SLN": "227311",
"LoName": "Elk GAF Materials Corp - Shafter",
"Type": "Shipper"
}
}, {
"value": {
"lineNumber": "258641",
"TypeId": "2",
"StopNumber": "2",
"ReferenceNo": "682383",
"LocationId": "205697",
"SLN": "227311",
"LoName": "RWC Building Products - Albuquerque",
"Type": "Consignee"
}
}
]
var table_obj = $('table');
$.each(data, function(index,value){
table_obj.append($('<tr><td>'+value.SLN+'</td><td >'+value.Type+'</td><td>'+value.StopNumber+'</td><td>'+value.LoName+'</td><td>'+value.ReferenceNo+'</td><td class="hide">'+value.TypeId+'</td><td class="hide">'+value.Locationid+'</td><td class="hide">'+value.lineNumber+'</td></tr>'));
The name you gave your variable "value" is confusing you. You still need to reference the "value" key within your object that just happens to be named value.
'+value.value.SLN+
Try this way .
value.value.SLN
Try this. All properties are inside value so you should try value.value
$.each(data, function(index, v){
var value = v.value;
table_obj.append($('<tr><td>'+value.SLN+'</td><td >'+value.Type+'</td><td>'+value.StopNumber+'</td><td>'+value.LoName+'</td><td>'+value.ReferenceNo+'</td><td class="hide">'+value.TypeId+'</td><td class="hide">'+value.Locationid+'</td><td class="hide">'+value.lineNumber+'</td></tr>'));
}
try this
for (var i in data)
console.log(data[i].value);
if it will output in console result, just use it as data[i].value.field