Pre-fill selectize menu? - javascript

I have a selectize-ng menu:
<input type="text" selectize="usersSelect.options" options="users" ng-model="users.selected" />
"users" is my array of objects. This menu works perfectly, I can select from the menu, type-ahead, and get tokenized names. My controller options are:
$scope.usersSelect = {
options: {
valueField: 'full_name',
labelField: 'full_name',
searchField: ['full_name'],
plugins: ['remove_button']
}
};
Except now I have another array of 6 "full_name" strings I need to be IN the menu at the start. I can't find any docs on how to pre-populate these menus. I'm using Angular 1.3.

You can set values to your model:
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/brianreavis/selectize.js/master/dist/js/standalone/selectize.min.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/kbanman/selectize-ng/master/dist/selectize-ng.js"></script>
</head>
<body data-ng-app="app" data-ng-controller="MainController">
<input type="text" selectize="config" options="suggestions" ng-model="selected"/>
<script>
var app = angular.module('app', ['selectize-ng']);
app.controller("MainController", function($scope, $timeout) {
$scope.config = {valueField: 'value',
labelField: 'text'};
$scope.suggestions = [{ value: 1, text: 'One' },
{ value: 2, text: 'Two' },
{ value: 3, text: 'Three' },
{ value: 4, text: 'Four' }];
$scope.selected = [$scope.suggestions[0]['value'], $scope.suggestions[3]['value']];
});
</script>
</body>
</html>

Looking at the other answer posted gave me the idea of assigning an array to selected, but the syntax in that answer gave me errors both in execution as in JSHINT.
So, I experimented until I got this:
_this.roleMenu = {
config: {
valueField: 'name',
labelField: 'name',
plugins: ['remove_button']
},
suggestions: _this.roles,
selected: []
};
_this.roleMenu.selected = [
_this.roleMenu.suggestions[2].name
];
For this menu in html:
<select selectize="invite.roleMenu.config" options="invite.roleMenu.suggestions" ng-model="invite.roleMenu.selected" />
This assumes my page controller to be InviteController as invite

Related

Can't pre-select options in Select2 multiple choice select box

I use the select2 jQuery module to create a multiple choice select box. I did this in an early version (3.4.5) and it worked fine. But after upgrade to 4.1.0 pre-selection of an option does not work.
My code looks like below,
HTML - part:
<input type="text" id="accessories" />
JS:
jQuery(document).ready(function() {
var acceArray2 = [{id:0,text:"textA"},{id:1,text:"textB"},{id:2,text:"textC"}];
jQuery("#accessories").select2({
data: acceArray2,
multiple: true,
placeholder: "",
width: 200
});
jQuery("#accessories").val("1");
jQuery("#accessories").trigger("change");
});
My options show up when I click in the box. I can also select one or more option. But I expect "textB" should be selected when I open the page. This works fine with the original select2 version, but not with 4.1.0. The box is just empty.
I have spent hours trying to figure what's wrong, but I can't....
Alternatively, you can change the input tag to select. It seems to work below:
jQuery(document).ready(function() {
const acceArray2 = [{
id: 0,
text: "textA"
}, {
id: 1,
text: "textB"
}, {
id: 2,
text: "textC"
}];
jQuery("#accessories").select2({
data: acceArray2,
multiple: true,
placeholder: "",
width: 200
});
jQuery("#accessories").val("1");
jQuery("#accessories").trigger("change");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<select id="accessories"></select>
You can add selected option in array object like:
jQuery(document).ready(function() {
var acceArray2 = [{
id: 0,
text: "textA"
}, {
id: 1,
text: "textB",
selected: true
}, {
id: 2,
text: "textC",
selected: true
}];
jQuery("#accessories").select2({
data: acceArray2,
multiple: true,
placeholder: "",
width: 200
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<input type="text" id="accessories" />

Append element to Datatable header

What I'd like to do is add a radio button next to the Search Bar on my datatable to allow searching by just one column, Store Number.
I was referred to drawCallback but I don't believe this does what I expect it to do. All the answers I find seem to be appending elements to rows/cols in the datatable, but not the header itself.
The selector for this header is #store-table_wrapper.
$('#store-table').DataTable({
"columnDefs": [{
"targets": [7, 8],
"visible": false,
"drawCallback": function() {
$('<input type="radio" name="store-number-filter-selector" />').appendTo('#store-table_wrapper');
}
}]
});
I believe, getting your radio button displayed you're half-way through, the really challenging part is to disable default search bar, since you're unlikely to override its default behavior (to search through the entire table).
However, you may use your own, custom searchbar, like on the following DEMO:
//define source data
const srcData = [
{id: 1, name: 'apple', category: 'fruit'},
{id: 2, name: 'raspberry', category: 'berry'},
{id: 3, name: 'carrot', category: 'vegie'}
];
//define dataTable object
const dataTable = $('#mytable').DataTable({
sDom: 't',
data: srcData,
columns: [
{data: 'id', title: 'id'},
{data: 'name', title: 'name'},
{data: 'category', title: 'category'}
],
//modify header nodes, by appending radios
initComplete: function() {
const table = this.api();
[1,2].forEach(column => table.column(column).header().innerHTML += `<input type="radio" name="searchflag" value="${column}" class="searchflag"></input>`);
}
});
//prevent sorting change upon radio click
$('input.searchflag').on('click', function(event) {
//clear search upon choosing the other radio
$('#searchfield').val('');
dataTable.search('').columns().search('').draw();
event.stopPropagation();
});
//searchbar keyup callback
$('#searchfield').on('keyup', function() {
//grab checked radio button value or search the entire table by default
let targetColumn = null;
targetColumn = $('input.searchflag:checked').val();
if(!targetColumn){
dataTable.search($(this).val()).draw();
}
else {
dataTable.column(targetColumn).search($(this).val()).draw();
}
})
input.searchflag {
float: left;
}
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<input id="searchfield"></input>
<table id="mytable"></table>
</body>
</html>

Angularjs: select not working when ng-model a json object

Once I use ng-options for a select I am unable to get dafault selection to work on nested json objects.
once I have a bit more complicated json and the select should handle a child object my select does not default select the proper value.
Given test = {"id":3,"title":"Test","product":{"id":4,"name":"Test1"}} as my ng-model test.product and
[{
"id": 4,
"name": "Test1"
}, {
"id": 5,
"name": "Test2"
}]
as my selection option. (see http://embed.plnkr.co/mpnislw77UBSEdHl4UKN/)
I seem to be unable to figure out how to facilitate default selection.
If you use track by item.id it works - http://embed.plnkr.co/mpnislw77UBSEdHl4UKN. The marked answer was not very obious since the ng-model is nested in iself. but it contains the correct information.
The only problem with your code is that you've assigned a new object to $scope.test.product and you're using it as the ng-model of the dropdown.
This makes AngularJS unable to find it inside the possible values, which are $scope.testarray. AngularJS will compare two objects by their reference, which you broke when you assigned a new object to $scope.test.product.
To make it working, change $scope.test as follows:
$scope.test = {
"id": 3,
"title": "Test",
"product": $scope.testarray[1]
}
This is how to select with ngOptions and setting a default value
Example
angular.module('defaultValueSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
],
selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
};
}]);
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body ng-app="defaultValueSelect">
<div ng-controller="ExampleController">
<form name="myForm">
<label for="mySelect">Make a choice:</label>
<select name="mySelect" id="mySelect"
ng-options="option.name for option in data.availableOptions track by option.id"
ng-model="data.selectedOption"></select>
</form>
<hr>
<tt>option = {{data.selectedOption}}</tt><br/>
</div>
</body>
</html>
try this, hope it will help
<option value="" ng-if="false"></option>

Dependent Select Angular JS

I have hierarchical data set. There is one fixed root unit.
What I want to do is to make this tree browsable with dependent selects.
I have created a simple plunkr example with a fixed dataset.
http://plnkr.co/edit/Bz5A1cbDLmcjoHbs5PID?p=preview
The data format in the example mimics the format I would get from a server request in "real" life.
This working fine in this simple first step. What is missing is, that when a user changes a selection somewhere in the middle, the select boxes and the ng-model binding below the new selection need to be destroyed.
So when I select Europe->France->Quimper and change "Europe" to "Asia" - then there should be "Asia" as the first select box and a second one the Asia countries.
Is there an "Angular" way to deal to deal with this? Any other hint is appreciated also ;)
<!DOCTYPE html>
<html ng-app="app">
<head>
<link data-require="bootstrap#3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script src="https://code.angularjs.org/1.3.17/angular.js" data-semver="1.3.17" data-require="angular.js#1.3.17"></script>
</head>
<body>
<div ng-controller="Ctrl">
<select ng-repeat="select in selects track by $index" ng-model="$parent.boxes[$index]">
<option ng-repeat="child in select.children" ng-click="expandSelects(child)">{{child.name}}</option>
</select>
<ul>
<li ng-repeat="item in boxes">{{ item }}</li>
</ul>
</div>
<script>
var app = angular.module('app', []);
app.controller('Ctrl', ['$scope', function($scope) {
var data = {
'europe': {
name: 'europe',
children: [{
name: 'france',
parent: 'europe'
}, {
name: 'italy',
parent: 'europe'
}],
},
'asia': {
name: 'asia',
children: [{
name: 'japan',
parent: 'asia'
}, {
name: 'china',
parent: 'asia'
}],
},
'france': {
name: 'france',
children: [{
name: 'paris',
parent: 'france'
}, {
name: 'quimper',
parent: 'france'
}]
}
};
var root = {
name: 'world',
children: [{
name: 'europe',
parent: 'world'
}, {
name: 'asia',
parent: 'world'
}, ]
};
$scope.selects = [root];
$scope.expandSelects = function(item) {
var select = data[item.name];
if (select) {
$scope.selects.push(select);
}
}
$scope.$watch('boxes', function(item, old) {
}, true);
}]);
</script>
</body>
</html>
This is a classic example of cascading dropdowns, with the added challenge of an unknown number of levels in the cascade. I combined the data set into one object for simplicity, added labels for the dropdowns, and simplified the select element.
This solution allows for any number of levels, so if you needed data below the city level, you could add it without changing any code, as illustrated by the "Street" example I added to Paris.
select {
display: block;
}
<!DOCTYPE html>
<html ng-app="app">
<head>
<link data-require="bootstrap#3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script src="https://code.angularjs.org/1.3.17/angular.js" data-semver="1.3.17" data-require="angular.js#1.3.17"></script>
</head>
<body>
<div ng-controller="Ctrl">
<div ng-repeat="select in selects track by $index" ng-if="select.children">
<label>{{ select.optionType }}</label>
<select ng-model="selects[$index + 1]" ng-options="child.name for child in select.children" ng-change="clearChildren($index)"></select>
<hr />
</div>
</div>
<script>
var app = angular.module('app', []);
app.controller('Ctrl', ['$scope', function($scope) {
var data = {
optionType: 'Continent',
name: 'World',
children: [
{
optionType: 'Country',
name: 'Europe',
children: [
{
optionType: 'City',
name: 'France',
children: [
{
optionType: 'Street',
name: 'Paris',
children: [
{
name: 'First'
},
{
name: 'Second'
}
]
},
{
name: 'Quimper'
}
]
},
{
name: 'Italy'
}
]
},
{
optionType: 'Country',
name: 'Asia',
children: [
{
name: 'Japan'
},
{
name: 'China'
}
]
}
]
};
$scope.selects = [data]
$scope.clearChildren = function (index) {
$scope.selects.length = index + 2;
};
}]);
</script>
</body>
</html>
To go to the children in your hierachy is not as hard as it may seem. If you set up your select with angular and let it do most of the selection for you (for example using ng-options instead of ng-repeating the tag itself), and tell it what options there are, then the list of children you are trying to render just becomes a standard ng-repeat of the children that were picked from the select above.
I modified your plunker to show you how you could accomplish that a slightly different way.
http://plnkr.co/edit/zByFaVKWqAqlR9ulxEBt?p=preview
Main points I changed were
$scope.expandSelects = function() {
var select = data[$scope.selected.name];
if (select) {
console.log('changed');
console.log(select);
$scope.chosen = select;
}
}
Here i just grab the chosen item which the will use. Then the ends up looking like.
<ul>
<li ng-repeat="item in chosen.children">{{ item.name }}</li>
</ul>
The only other set up that was really needed was setting up the with ng-options and giving it a model to bind to.
<select ng-options="child.name for child in selects.children"
ng-model="selected" ng-change="expandSelects()">
</select>
Use can use a filter on the second select to filter de options based on the previous selection.
For example, you can have a first selection to choose the continent:
<select ng-options="c for c in continents" ng-model="selectedContinent" ></select>
and a second selection for the coutries:
<select ng-options="c.name for c in countries | filter : {parent:selectedContinent}" ng-model="selectedCountry" ></select>
Made a fiddle with a simplified data structured just to show how the filter works: http://jsfiddle.net/marcosspn/oarL4n78/

JQWidgets jqxGrid with jqxDropDownList as editor

Could someone provide the proper implementation method for utilizing the jqxDropDownList with checkboxes enabled as a grid column?
The following code is modified from the jqwidgets grid demo code ‘cellediting.htm’.
I've implemented an independent dropdownlist with checkboxes with no problems.
I've implemented a grid with dropdownlist (with out checkboxes) with no problems.
however, as soon as i put checkboxes: true in the initeditor i get the following error:
Uncaught TypeError: Cannot read property ‘instance’ of undefined jqxlistbox.js:7
In certain ‘more complicated’ scenarios, the checkboxes property will succeed with ‘createeditor’, but fail with initeditor.
This leads me to believe there is probably some asynchronous loading going on and im building the editor too quickly.
The following code fails because of the ‘checkboxes: true’ property. remove that and it works great.
<head>
<title id='Description'>In order to enter in edit mode, select a grid cell and start typing, "Click" or press the "F2" key. You
can also navigate through the cells using the keyboard arrows or with the "Tab" and "Shift + Tab" key combinations. To cancel the cell editing, press the "Esc" key. To save
the changes press the "Enter" key or select another Grid cell. Pressing the 'Space' key when a checkbox cell is selected will toggle the check state.</title>
<link rel="stylesheet" href="../../jqwidgets/styles/jqx.base.css" type="text/css" />
<script type="text/javascript" src="../../scripts/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxdata.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxscrollbar.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxmenu.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxgrid.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxgrid.edit.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxgrid.selection.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxgrid.filter.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxlistbox.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxdropdownlist.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxcheckbox.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxcalendar.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxnumberinput.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxdatetimeinput.js"></script>
<script type="text/javascript" src="../../jqwidgets/globalization/globalize.js"></script>
<script type="text/javascript" src="../../scripts/gettheme.js"></script>
<script type="text/javascript" src="generatedata.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// prepare the data
var data =
[
{ firstname: 'joe', lastname: 'smith', sex: 'm' },
{ firstname: 'john', lastname: 'doe', sex: 'm' },
{ firstname: 'jane', lastname: 'doe', sex: 'f' }
];
var source =
{
localdata: data,
datatype: "array",
updaterow: function (rowid, rowdata, commit) {
commit(true);
},
datafields:
[
{ name: 'firstname', type: 'string' },
{ name: 'lastname', type: 'string' },
{ name: 'sex', type: 'string' }
]
};
var dataAdapter = new $.jqx.dataAdapter(source);
// initialize jqxGrid
$("#jqxgrid").jqxGrid(
{
width: 685,
source: dataAdapter,
editable: true,
selectionmode: 'multiplecellsadvanced',
columns: [
{ text: 'First Name', columntype: 'textbox', datafield: 'firstname', width: 80 },
{ text: 'Last Name', columntype: 'textbox', datafield: 'lastname', width: 80 },
{ text: 'Sex', columntype: 'dropdownlist', datafield: 'sex', width: 195,
createeditor: function(row, cellvalue, editor)
{
var mydata =
[
{ value: "m", label: "Male" },
{ value: "f", label: "Female" }
];
var mysource =
{
datatype: "array",
datafields:
[
{ name: 'label', type: 'string' },
{ name: 'value', type: 'string' }
],
localdata: mydata
};
var myadapter = new $.jqx.dataAdapter(mysource, { autoBind: true });
editor.jqxDropDownList({ checkboxes: true, source: myadapter, displayMember: 'label', valueMember: 'value' });
}
}
]
});
// events
$("#jqxgrid").on('cellbeginedit', function (event) {
var args = event.args;
$("#cellbegineditevent").text("Event Type: cellbeginedit, Column: " + args.datafield + ", Row: " + (1 + args.rowindex) + ", Value: " + args.value);
});
$("#jqxgrid").on('cellendedit', function (event) {
var args = event.args;
$("#cellendeditevent").text("Event Type: cellendedit, Column: " + args.datafield + ", Row: " + (1 + args.rowindex) + ", Value: " + args.value);
});
});
</script>
</head>
<body class='default'>
<div id='jqxWidget'>
<div id="jqxgrid"></div>
<div style="font-size: 12px; font-family: Verdana, Geneva, 'DejaVu Sans', sans-serif; margin-top: 30px;">
<div id="cellbegineditevent"></div>
<div style="margin-top: 10px;" id="cellendeditevent"></div>
</div>
</div>
</body>
</html>
Can anyone offer assistance?
Extra help!!
Additionally, it seems like once i select a value in the dropdown, the actual ‘value’ gets changed to the display ‘label’. i.e., (“Male” or “Female”), but in this example, the only valid data for the sex field would be ‘m’ or ‘f’.
I've asked the same question on the jqwidgets official forums (here: http://www.jqwidgets.com/community/topic/dropdownlist-with-checkboxes-as-grid-column-editor/), and will post any answer they send here if they beat the community to it.
As far as I know, there is no DropDownList with Checkboxes Editor in the jQwidgets Grid. If there was such, I think that jQWidgets would at least have a sample about it so I suppose that you cannot use the DropDownList in such way in the jqxGrid widget.
I know that this is a rather old post, but still...
I'm surprised to see the response from the JQWidgets team, since they themselves have such an example on their website, using a dropdownlist with checkboxes as a grid editor.
It is available at http://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/index.htm#demos/jqxgrid/cellcustomediting.htm
where the editor is used in the Products column.
Mihai

Categories