Semantic UI dropdown lists displays 'undefined' - javascript

I'm having difficultly getting a Semantic UI (v2.4.2) dropdown to work as expected.
If I click the down arrow, the dropdown displays a list of undefined items:
If I type the name of a tag, the dropdown displays the correct list of tags:
HTML:
<div id="myList" class="ui multiple search selection dropdown">
<input type="hidden" name="tags">
<i class="dropdown icon"></i>
<div class="default text">Tags</div>
</div>
<script type="text/javascript">
$("#myList").dropdown({
minCharacters : 3,
allowAdditons : true,
apiSettings : {
url : '//localhost:9393/tags/search?q={query}',
onResponse: function(tags) {
console.debug('onResponse');
var response = {
success: true,
results: []
};
$.each(tags, function(index, item) {
response.results.push({
name: item.name,
value: item.id
});
});
return response;
}
}
});
</script>
The JSON API returns a list of tags as an array:
[
{
"id": 5,
"name": "mssql",
"description": "Microsoft SQL Server is a relational, database-management system developed by [Microsoft](https://www.microsoft.com/)."
},
{
"id": 6,
"name": "oracle",
"description": "Oracle's DBMS"
},
{
"id": 8,
"name": "plsql",
"description": "[PL/SQL](https://en.wikipedia.org/wiki/PL/SQL) is Oracle Corporation's procedural extension for SQL and the Oracle relational database."
}
]
Oddly, the onResponse callback only fires when a value is typed in the search box.
What am I missing?

you've set the minimum number of characters to initiate the search to 3 right here:
$("#myList").dropdown({
minCharacters : 3,
allowAdditons : true
simply add:
showOnFocus:true
to your configuration object. It should solve the problem.

Related

Create dynamic checkboxes using jquery from JSON data

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>

AngularJS Dynamically Creating Select Box - ngModel Not Registering

I am using one select box to conditionally generate a second select box. The select boxes populate correctly and everything looks okay in the Chrome Inspector on the elements.
The problem is the ng-model (ng-model="commandName" in the code example below) does not properly register the correct select value. So, if you look in the example, the {{commandName}} output at the end correctly outputs for the first select box but for the second select box nothing is output.
Is this a bug? Can anyone recommend an alternate method for approaching this problem?
Everything appears to work except commandName does not output anything in the p tag at the bottom but commandType does.
<select ng-model="commandType" class="form-control" ng-init="commandType = ''; command = ''">
<option value=""></option>
<option ng-repeat="commandGroup in commandList" value="{{$index}}">{{commandGroup.name}}</option>
</select>
<!-- Shown if something is selected in the select box above -->
<select ng-model="commandName" class="form-control" ng-if="commandType !== ''">
<option value=""></option>
<option ng-repeat="exactCommand in commandList[commandType].commands" value="{{$index}}">{{exactCommand.name}}</option>
</select>
<p>{{commandName}}</p>
AngularJS code:
$scope.initCommandList = function () {
$http({
method: 'GET',
url: $rootScope.webserver + 'admin/rterminalCommandList/',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data) {
console.log("Command list");
console.log(data.data);
$scope.commandList = data.data;
});
};
$scope.initCommandList();
And POST response:
{
"data"
:
[{
"id": 2,
"name": "Application",
"commands": [{
"id": 3,
"name": "Delete Smartcare data",
"syntax": "su -c pm clear com.patasonic.android.smartcare",
"comment": "Deletes Smartapp data"
}]
}, {
"id": 1,
"name": "Bluetooth",
"commands": [{
"id": 2,
"name": "Bluetooth Controls. Turn off",
"syntax": "bluetooth# off",
"comment": "Turns off device bluetooth"
}, {"id": 1, "name": "Bluetooth Controls. Turn on", "syntax": "bluetooth# on", "comment": "Turn on bluetooth"}]
}], "header"
:
{
"messages"
:
[], "response_code"
:
200
}
}
I recommend you to use "select ng-options" instead of "option ng-repeat"
https://docs.angularjs.org/api/ng/directive/ngOptions
<select ng-model="myModel"
ng-options="command as command.name for command in commandList">
</select>
Here is a jsfiddle with an example:
http://jsfiddle.net/jcamelis/5y086ytr/4/
I hope it helps.

Proper display of layered json data

I have json that looks like this:
[
{
"Id": 1,
"Name": "Item1",
"Order": 1,
"Categories": [
{
"Id": 1,
"Name": "Item1-Subitem1",
"Order": 1,
"Subcategories": [
{
"Id": 1,
"Name": "Item1-Subitem1-Subsubitem1",
"Order": 2
},
{
"Id": 2,
"Name": "Item1-Subitem1-Subsubitem2",
"Order": 1
},
...
and with angular I need to display on first page (or route) link on main items. For example:Item1Item2And when clicked on them links should be displayed with names from 'Categories'For example:Item1-Subitem1Item1-Subitem2And when clicked on these links there should be displayed links with name from 'Subcategories'For example:Item1-Subitem1-Subsubitem1Item1-Subitem1-Subsubitem2
Now my first links work but I don't know how to get that nested data from same json according to value from url. When I click on links in first view I go to page I need but without data. No errors is displayed. I belive I need to parse id from url but how to achieve that?
It can be checked here http://plnkr.co/edit/GTfLFQepFcXzXYcIHnP0I am using ui-router
In secondList.js, you've defined your scope with the wrong name. It should be:
scope: {
secondList: '='
},
After you fix that, you're also missing the final factory in service.js:
app.factory('singleList', ['$http', function ($http) {
return {
get: function () {
return $http.get('data.json').then(function (re) {
return re.data;
});
}
};
}])

Autocomplete using bootstrap typehead working fine but i need corresponding value

Working on bootstrap typehead for autocomplete. With the help of the typehead documentation the autocomplete working fine but when I select the particular value from autocomplete i need to get the relevant name in the label field.
This is my HTML code.
<input type="text" class="ipt_Field" id="txt_schName" name="txt_schName" />
<label id="school_Name"></label>
This is my json data
["COL000001,Emirates College of Technology- UAE","COL000002,Al Khawarizmi International College- UAE","COL000003,Syscoms College","COL000004,Abounajm Khanj Pre-Uni Center","COL000005,Advanced Placement","COL000006,Al Buraimi College (Uni Clge)","COL000007,Al-Ain Community College","COL000008,AMA Computer College","COL000009,Arab Academy for Bankg and Fin","COL0000010,ARABACDSCITECHMARTIMETRNS","COL0000011,Arapahoe Community College"]
This is my jquery code
$("#txt_schName").typeahead({
name: 'School Name',
// data source
prefetch: 'json/school_name.json',
// max item numbers list in the dropdown
limit: 5,
minLength:3
});
Kindly please guide me how to get the corresponding vaule to the label. I am struggling lot.
Thanks & Regards
Mahadevan
To keep a simple key / value pair, split-up your data into an array of objects.
For example:
var aData = [{
"iso": "DE",
"desc" : "Germany"
}, {
"iso": "FR",
"desc" : "France"
}, {
"iso": "CA",
"desc" : "Canada"
}, {
"iso": "NO",
"desc" : "Norway"
}];
Configure your typeahead.js as follows
$(function () {
var bhData = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace("desc"),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: aData
});
$('.typeahead').typeahead(null, {
name: 'countrylist',
display: 'desc',
limit: 50,
source: bhData,
templates: {
empty: ['<div class="empty-message">', 'unable to find country', '</div>'].join('\n'),
suggestion: function (data) {
return '<p><strong>' + data.iso + '</strong> ' + data.desc + '</p>';
}
}
});
// Capture selected event and output the selected key / value data
$('.typeahead').on('typeahead:selected', function (event, data) {
$("#iso").html( data.iso );
$("#desc").html( data.desc );
});
});
Here's a link to a full working example https://jsfiddle.net/W_Walseth/uL4Lkmdt/4/

FormatSelection in select2Option is removing data

FormatSelection in select2Option removing data.
I am receiving my data in
$scope.superclasses = superclassDataList.data;
where superclassDataList is coming from service in angular.
Data i received from service is :
{
"data": [{
"name": "new Test",
"id": 4506898162253824,
"attendanceAllowed": true,
"subclasses": [{
"title": "HIN",
"children": null,
"entityName": "MyClass",
"entityId": 5136918324969472
},
{
"title": "ENG 101 A",
"children": null,
"entityName": "MyClass",
"entityId": 5699868278390784
}]
}
],
"success": true,
"errorMessage": ""
}
Code where i am applying my ng-grid to show this data:
<div ng-show="superclasses[row.rowIndex].edit"><div id="subclasses" ng-model="superclasses[row.rowIndex].subclasses" ui-select2="select2Options" data-placeholder="Add Subclasses" style="width:100%" multiple></div></div>
<div class="ngCellText" ng-class="col.colIndex()" style="display:inline" ng-show="!superclasses[row.rowIndex].edit" ng-repeat="subclass in superclasses[row.rowIndex].subclasses">{{subclass.title}} ,</div>
(I added one extra field "edit" in superclasses so don't be confuse with that. If it's true first div(Editable mode) will be visible else second(View mode))
Code for select2 i write is:
$scope.subclassNameFormat="";
$scope.select2Options = {
allowClear : true,
multiple: true,
width : 550,
minimumInputLength: 3,
query: function (query){
SuperclassService.getSubclassesUnassigned({searchTerm: query.term.toUpperCase()}, function(response) {
$scope.classesList = response.data;
var data = {
results: []
};
$.each($scope.classesList, function(){
if(this.list === undefined || this.list.length === 0) {
data.results.push({id: this.id, text: this.title,isApplied: false});
}
});
query.callback(data);
}, function(error){
console.log("Superclass is not deleted.... Please try again");
});
},
formatSelection: function format(state) {
if((state.title === undefined || state.title === "") && (state.text !== undefined && state.text !== "")){
$scope.subclassNameFormat = state.text;
}else if((state.text === undefined || state.text === "") && (state.title !== undefined && state.title !== "") ){
$scope.subclassNameFormat = state.title;
}
}
};
here getSubclassesUnassigned() method retrieve data from server on the basis of 3 character i entered to search: (minimumInputLength: 3),
Question: The data in $scope.superclasses comes from server is complete(JSON Data written above). And for a moment complete data of subclasses visible(when edit is false) (in this case name of subclasses HIN, ENG 101 A). Once it entered in "formatSelection" part of "$scope.select2Options" one data from "subclasses" array will be remove and it reflect on the "subclasses" column in grid (the code i write above) and show only one name (either "HIN" or "ENG 101 A"). I don't know why it get entered in "formatSelection" part of "select2options" because till data time "edit" field was false. (See in div code ng-show="!superclasses[row.rowIndex].edit" ). I don't know how it reflect the data. and even delete the data completely(2nd object of subclasses array.).
Have a same problem when value of div is in editable mode(ng-show="superclasses[row.rowIndex].edit") it only show one value of subclasses array.
data after passing control from FormatSelection:
{
"data": [{
"name": "new Test",
"id": 4506898162253824,
"attendanceAllowed": true,
"subclasses": [{
"title": "HIN",
"children": null,
"entityName": "MyClass",
"entityId": 5136918324969472
}]
}],
"success": true,
"errorMessage": ""
}
I tried everything from reading complete doc. about query and formatSelection from select2 but didn't find or understand anything, and also search on stackoverflow but didn't find any relevant link or didn't understand from those already on site. I know it might be silly question for some professionals but i started working on angular just 2 days ago.
Ask me in more explanation is required. I will try to provide everything that i know.
Thanks in advance.
PS: Please ignore My grammatical mistakes.
Try this code before "query :" in select2Option
initSelection: function(element, callback) {},
It will initialize your data for select2 which you are receiving in $scope.superclasses. It is working fine for me.

Categories