Create dynamic checkboxes using jquery from JSON data - javascript

I haven't found a solution online to this yet, if its available i would love to check it out. I would like to be able to create dynamic checkboxes based on selection from a dropdown, basically the dropdown looks something like this
<select>
<option value="Computer">Volvo</option>
<option value="Vehicle">Saab</option>
</select>
I have an accessories table in the database storing accessories that should be displayed to the user.
id | category | name |
----------------------------
1 | computer | mouse |
2 | computer | keyboard |
2 | vehicles | Roof-rack |
I would like to have a scenario where the user selects a category in the dropdown then a group of check boxes are dynamically created based on the name of accessories in the table. I'm using the code below that should return
a JSON of accessory names.
$.get("{{config('app.url') }}/hardware/models/"+catid+"/accesories",{_token: "{{ csrf_token() }}"},function (data) {
});
EDIT: the data returned looks somethink like;
{
"computer": [{
"id": "1",
"name": "mouse"
},
{
"id": "2",
"name": "keyboard"
},
{
"id": "1",
"name": "mouse"
}
]
}
For example: if a user selects computer from the dropdown then there should be checkboxes of accessories like keyboard, mouse, etc generated dynamically. Hope you can help me out. I am using laravel if that's important. Thanks

It will be better to return an array of objects instead, then you could iterate every accessory and generate the proper related checkbox like the following example shows :
$.get("{{config('app.url') }}/hardware/models/"+catid+"/accesories",{_token: "{{ csrf_token() }}"},function (data) {
data = $.parseJSON(data);
data.forEach( function (obj){
$('#dynamic_div').append('<input name="accesories" type="checkbox" value="'+obj.id+'"/> '+obj.name +'<br/>');
});
});
NOTE : If you cant' change the returned result you could change just the parse line to :
data = $.parseJSON(data['computer']);
But you should take in your consideration that 'computer' should be changed dynamically as a variable.
Hope this helps.
var arr = [{
"id": "1",
"name": "mouse"
},
{
"id": "2",
"name": "keyboard"
},
{
"id": "1",
"name": "mouse"
}
];
arr.forEach( function (obj)
{
$('#dynamic_div').append('<input name="accesories" type="checkbox" value="'+obj.id+'"/> '+obj.name +'<br/>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dynamic_div"></div>

Related

Create dynamic form with parameters

On a grid I have to create a (popup) form dynamically, based on a JSON that has the data for what type of input goes on the form.
For the select type, the options are different for every form, and all the options are in another JSON that is called based on the name on the previous JSON.
example.
I click on button "create report" for row number 1 on grid. popup open up with form to get the filter of the report. the button call the 1st JSON that is like this:
[
{
"name": "Report Users residence",
"input": [{
"type": "select",
"name": "city",
},
{
"type": "select",
"name": "address",
}]
}
]
In this case the cities are in another JSON called "city.json".
[
{
"code": "000000",
"description": "City1"
},
{
"code": "000001",
"description": "City2",
}
]
I was able to create the form, but i don't know how to get the option of the 2nd JSON on the select "city".Can someone give me an example on how to do it?
First, city data have to converted into object. After that using jQuery $.each method, you can loop over city object to create option for select and append into the select.
This is an example of the idea :
<select name="city"></select>
<script>
var city = [{"code":"000000","description":"City1"},{"code":"000001","description":"City2",}];
var citySelect = $(document).find('select[name="city"]');
$(city).each(function(key,item){
var cityOption = new Option(item.description,item.code);
citySelect.append(cityOption);
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="city"></select>
<script>
var city = [{"code":"000000","description":"City1"},{"code":"000001","description":"City2",}];
var citySelect = $(document).find('select[name="city"]');
$(city).each(function(key,item){
var cityOption = new Option(item.description,item.code);
citySelect.append(cityOption);
});
</script>

retrieve firebase database json

l am trying to retrieve all data in a firebase database . When l used this code <h1>{{ item | async | json }}</h1> depending on doc of angularfire2 object l got list of json response object in html
{
"type": "value",
"payload": {
"8D3sENaBcLaXoGNnh1MPuoyj5LP2": {
"-LWl294Hs6YjkvJE5pqi": {
"name": "ddd",
"title": "dd"
},
"-LWlEonKLWfOttzirqp7": {
"name": "sas",
"title": "ass"
},
"-LWlGvn81Kes2A-1UcC2": {
"name": "asa",
"title": "asass"
},
"-LWlK92A7gaRkKVrZSFU": {
"name": "ddd",
"title": "ddd"
},
"-LWla1PYxsIFKhaCXvtu": {
"name": "ff",
"title": "fdsf"
},
"-LWpfRJP8VdwG927wyXS": {
"name": "ali",
"title": "ali"
},
"-LWph3ei12KTNyirdnZb": {
"name": "ddddd",
"title": "daD"
}
},
"WUM2HBkGo8TFDeOjEqO1s3lCj1p1": {
"-LWlHlhyS9m3ECS3wIdk": {
"name": "qwqsasasa",
"title": "as"
},
"-LWlHmXZAJdSPZurO7ii": {
"name": "qwqsasasa",
"title": "as"
},
"-LWph-fv4JMtTk22aE5X": {
"name": "sssssssssssssssssssssssss",
"title": "sssssssssssssssssssssssss"
}
}
},
"key": "report"
}
l want to get from this list json object only title and name . l used this code but l got empty page in html no data to show !
<h1>{{ (item | async)?.name }}</h1>
<h1>{{ (item | async)?.title }}</h1>
main code
itemRef: AngularFireObject<any>;
item: Observable<any>;
ionViewWillLoad(){
this.fire.authState.subscribe(data => {
if(data && data.email && data.uid){
this.toastCtrl.create({
message : ` welcome ${data.email}`,
duration:2000
}).present()
this.itemRef = this.db.object('report');
this.item = this.itemRef.snapshotChanges();
}
})
}
The /report key in your database seems to hold a list of objects: specifically a list of reports for each user, so with two nested keys under /report. But your code is loading it as a single object. This leads to this HTML <h1>{{ (item | async)?.name }}</h1> essentially displaying /report/name, which doesn't exist in your database.
If you want to display the name and title of a single report, you need to know the keys of that report. For example to show the first report for the first user:
this.itemRef = this.db.object('report/8D3sENaBcLaXoGNnh1MPuoyj5LP2/-LWl294Hs6YjkvJE5pqi');
The first subkey 8D3sENaBcLaXoGNnh1MPuoyj5LP2 here is the UID of the user whose report you're showing and the -LWl294Hs6YjkvJE5pqi is the first report of that user.
If you want to display all reports for a user, you will need to again know the key of the user and pass it into the database. But since you then get back a list of reports, you'll also need to use the list service from AngularFire and loop over the results in your HTML template, so that it generates the elements for each report:
this.reports = this.db.list('report/8D3sENaBcLaXoGNnh1MPuoyj5LP2');
And:
<ul>
<li *ngFor="let report of reports | async">
{{ item.title }} - {{ item.name }}
</li>
</ul>
If you want to display a nested list of all reports for all users, you'd start with the same as just above, but now load the data for all users, and use another ngFor to loop over the users first.
Also see:
the AngularFire documentation on lists
this tutorial on building a CRUD application with AngularFire

dependent dropdownlist with json and python

So I am making a dialog panel for my chat bot in django framework. The Dialog panel consists of intent and entities dropdown list and a dialog textarea. The dropdown list will be dependent on my training data which is in json format.
I want the dropdownlist so that if I choose intent, the entities dropdown list create itself automatically and show all the entities related to selected intent.
I have tried and I am able to show intent dropdown but that too had duplicate intents(which i removed using python set function).But I am unable to figure out how to show all entities based on one particular intent.
Help me. Here's my example json:
{"rasa_nlu_data": {
"common_examples": [
{
"text": "hey",
"intent": "greet",
"entities": []
},
{
"text": "yep",
"intent": "affirm",
"entities": []
},
{
"text": "i'm looking for a place to eat",
"intent": "restaurant_search",
"entities": []
},
{
"text": "i'm looking for a place in the north of town",
"intent": "restaurant_search",
"entities": [
{
"start": 31,
"end": 36,
"value": "north",
"entity": "location"
}
]
},
{
"text": "show me chinese restaurants",
"intent": "restaurant_search",
"entities": [
{
"start": 8,
"end": 15,
"value": "chinese",
"entity": "cuisine"
}
]
},
{
"text": "bye",
"intent": "goodbye",
"entities": []
}
]}}
Basically, all you have to do is loop over the items inside common_examples and check if the intent matches the selected value in the dropdown. If it does, add the entities to entities dropdown.
Since you haven't provided much info about your HTML, I'll try to answer with a few assumptions:
You've a select element with id intentDropdown to show intents.
You've a select element with id entitiesDropdown to show entities.
You're using jQuery.
The code contains some comments to explain what it does.
<!-- intents dropdown -->
<select id="intentsDrowpdown">
<!-- intent options-->
</select>
<!-- entities dropdown -->
<select id="entitesDrowpdown"></select>
<!-- Javascript -->
<script>
var data = {"rasa_nlu_data": { ... }}; // the json data
var totalExamples = data.rasa_nlu_data.common_examples.length; // total items inside common_examples
// listen to the event when selected value in
// the intent dropdown changes
$("#intentsDropdown").on('change', function() {
$("#entitiesDropdown").empty(); // clear the previously added entities from entities drowpdown
var selectedIntent = this.value; // currently selected intent
// loop over the items in common_examples
for (var i = 0; i < totalExamples; i++) {
var currentExample = data.rasa_nlu_data.common_examples[i] // current example in the loop
// see if the selected intent matches the
// intent of the current example in the loop
if (currentExample.intent == selectedIntent) {
// if intent matches
// loop over the items inside entities
// of the current example
for (var j = 0; j < currentExample.entities.length; j++) {
// add the option in the dropdown
$("#entitiesDropdown").append($('<option>', {
value: currentExample.entities[j].value,
text: currentExample.entities[j].entity
}));
}
}
}
});
</script>
Finally, I'd like to bring one thing to your notice. Conside the example below:
"entities": [
{
"start": 8,
"end": 15,
"value": "chinese",
"entity": "cuisine"
}
The entities list has one item in it. And that item has 4 sub-items in it. In your question, you haven't made it clear if you want to show all the sub-items in one dropdown option (e.g. start: 8, end: 15, value: chinese, entity: cuisine) or if you want a separate option for each sub-item.
The JS code that I've posted will create a dropdown option like this:
<option value="chinese">cuisine</option>.
If you want to display other items, you can just create another loop and keep adding the items to dropdown.

Automatically Populated Empty Value In ng-model ,data getting from ng-options

I Have List of Object I am Iterating using ng-options inside select tag
For that list of object has empty value below I posted my sample data I highlighted that empty data also I posted my code .
JSON DATA:
$scope.dummyData = [
{
"id": "0a40f753-0919-4bb2-b64e-74a280695ac6",
"buildName": "JackPot",
"department": "",
"floor": "",
"roomno": "12345Room",
"wing": "TEST"
},
{
"id": "1ff0d1e3-c347-41ce-8b96-acb695bba7a8",
"buildName": "JackPot",
"department": "Dept",
"floor": "Testing",
"roomno": "123f",
"wing": "Test"
}
]
above JSON data has floor:"" empty value .
Code:
<select ng-model="buildNameng" ng-options="option.floor as option.floor for option in dummyData | unique:'buildName'" style="width:12%" ng-change="buildCh(buildNameng)">
<!-- You can have ONE default, null selection option.--
<option value="">---Building---</option>
</select>
If the $scope.dummyData Json floor has empty the dropdown automatically changed in to empty value. The problem here is if I am getting an Empty value Inside floor like above JSON .The ng-model="buildNameng" automatically populated that empty value even if that has one more not null value . The ng-model buildNamengautomatically Populated into empty data first . I dont Know How to control this ?
I know another way the above select tag in no-options change like this I got the output but purposefully I dont want like this .
ng-options="option.id as option.floor for option in dummyData | unique:'buildName'"
I need to control that empty data automatically populated in program thats the problem also. Please guide me I am searching a lot but I couldn't find
Iterate through the chosenCat array with a for loop and remove every array item that does not have a defined floor before displaying the data.
var dummyData = [
{
"id": "0a40f753-0919-4bb2-b64e-74a280695ac6",
"buildName": "JackPot",
"department": "",
"floor": "",
"roomno": "12345Room",
"wing": "TEST"
},
{
"id": "1ff0d1e3-c347-41ce-8b96-acb695bba7a8",
"buildName": "JackPot",
"department": "Dept",
"floor": "Testing",
"roomno": "123f",
"wing": "Test"
}
];
for(var i = 0; i < dummyData.length; i++) {
if (!dummyData[i].floor); {
dummyData.splice(i, 1);
}
}
$scope.dummyData = dummyData;
I guess you're using angular-filter, so you can simple use the angular-filter#removewith filter, as below:
removeWith: { floor: '' }
Take a look on this simple example:
(function() {
'use strict';
angular
.module('app', ['angular.filter'])
.controller('mainCtrl', mainCtrl);
function mainCtrl($scope) {
$scope.dummyData = [
{
"id":"0a40f753-0919-4bb2-b64e-74a280695ac6",
"buildName":"JackPot",
"department":"",
"floor":"",
"roomno":"12345Room",
"wing":"TEST"
},
{
"id":"1ff0d1e3-c347-41ce-8b96-acb695bba7a8",
"buildName":"JackPot2",
"department":"Dept",
"floor":"Testing",
"roomno":"123f",
"wing":"Test"
}
];
}
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.9/angular-filter.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<select ng-model="buildNameng" ng-options="option.floor as option.floor for option in dummyData | unique: 'buildName' | removeWith: { floor: '' }">
<option value="">---Building---</option>
</select>
</body>
</html>
I hope it helps.

ng-repeat filter by existing array values

so I'm working with a basic product category model to get my head around filtering and I can't figure out how to extract a property value from one object within an array while repeating through another.
A simplified version of my category array, which is in scope, looks like this. I can output their names with the preceding directive and the results are as expected:
[{
"_id": "TY76",
"name": "Planes"
}, {
"_id": "887T",
"name": "Trains"
}, {
"_id": "A0K4",
"name": "Autos"
}]
<p ng-repeat="category in product.categories "> {{ category.name }}</p>
And here is a simplified product, also in scope, which may contain the ID of one or more categories. In this case, Bobble Head belongs to both Planes and Autos:
{
"_id": "9876",
"name": "Bobble Head",
"cats": "['TY76','A0K4']"
}
Now, here is where I'm having a hard time. I need to output the category names with the product. I can output the IDs no problem via:
<p ng-repeat="cat in product.cats ">{{ cat }}</p>
But that's of no use to the end user but I have no idea how to end up with something like:
Product: Bobble Head | Categories: Planes, Autos
I don't have the autonomy to add the category name to each product and I've tried a bunch of different filtering approaches but I don't think I'm wording my question right or something because I'm not finding much on the interwebs about this.
Any ideas?
Sounds like you want to build up a lookup for category id to category name:
var categories = [{
"_id": "TY76",
"name": "Planes"
}, {
"_id": "887T",
"name": "Trains"
}, {
"_id": "A0K4",
"name": "Autos"
}];
// build a category lookup id -> name
var categoryLookup = {};
categories.forEach(function(category) {
categoryLookup[category._id] = category.name;
});
Here's a full working fiddle: http://jsfiddle.net/02qadem7/1/
You can create a key-pair object where the key is the id and the value is the name of the category:
var categoriesArray = [{
"_id": "TY76",
"name": "Planes"
}, {
"_id": "887T",
"name": "Trains"
}, {
"_id": "A0K4",
"name": "Autos"
}];
$scope.categoriesMap = {};
categoriesArray.forEach(function(category) {
$scope.categoriesMap[category._id] = category.name;
});
Then in your view you can access the category name like this:
<div ng-repeat="product in products">
<strong>Product: </strong> {{product.name}} |
<strong>Categories: </strong> <span ng-repeat="category in product.cats">
{{categoriesMap[category]}}
</span>
</div>
Here's a plunkr: http://plnkr.co/edit/BpBcCizzU2Vh8VPniiHA?p=preview
I sugest using a custom filter on categories array.
myApp.filter('byCategoryIds', function() {
return function(categories, catIds) {
return categories.filter(function(item) {
return (catIds.indexOf(item._id) != -1);
});
};
});
Then you can iterate on categori array sending ids array like so:
<b>Product:</b>
{{product.name}};
<b>Categories:</b>
<span ng-repeat="cat in categories | byCategoryIds: product.cats">{{ cat.name }}, </span>

Categories