How to hide a selectize option programmatically? - javascript

I currently have a selectize drop-down that is suppose to have some options in it disabled and hidden depending on a list of strings that I have. Here is the non-selectize javascript function that I tried:
<!DOCTYPE html>
<html>
<body>
<select onchange="ToggleSelectizeOptions(this.value)">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
<option value="ford">Ford</option>
<option value="hyundai">Hyundai</option>
<option value="honda">Honda</option>
<option value="porsche">Porsche</option>
</select>
<select id="selectize">
<option value="">All Vehicles</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
<option value="ford">Ford</option>
<option value="hyundai">Hyundai</option>
<option value="honda">Honda</option>
<option value="porsche">Porsche</option>
</select>
<script>
function ToggleSelectizeOptions(ids) {
var selectizeOptions = document.getElementById("selectize").options;
var selectizeSingleOption;
//We always start at 1 because index 0 always have "" as the value.
for (var idx = 1; idx < selectizeOptions.length; idx++) {
selectizeSingleOption = selectizeOptions[idx];
if (ids) {
if (ids.includes(selectizeSingleOption.value)) {
selectizeSingleOption.style.display = "";
} else {
selectizeSingleOption.style.display = "none";
}
} else {
selectizeSingleOption.style.display = "";
}
}
}
</script>
</body>
</html>
This works with dropdowns that are not selectize controls but I'm looking for a solution that would use selectize.js to do the same thing.
I saw this question that is similar to what I want, except the answer disables the option while I want to hide the option.

I am not aware of a way to "hide" selectize options (with display css or otherwise) other than simply removing them from the options array that is created when you initialize a selectize control. If that is all that you need to do, then you can remove a selectize option by using the selectize removeOption(value) method (see the working snippet below for an example).
Based on your code example, it looks like your ultimate goal is to create cascading dropdowns. If so, see the 2nd snippet below for an example.
const sel1 = $('#select1').selectize();
sel1[0].selectize.removeOption('ford');
sel1[0].selectize.refreshOptions();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Selectize</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.default.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.js"></script>
</head>
<body>
<select id="select1">
<option value="ford">Ford</option>
<option value="honda">Honda</option>
</select>
</body>
</html>
If your ultimate goal is to create cascading dropdowns where the value selected in the first select element determines which options are available in a second select element. The snippet below initializes the options in the javascript rather than the html.
const models = [{text: 'Models', value: ''}];
const makes = [
{text: 'Makes', value: ''},
{text: 'Ford', value: 'ford'},
{text: 'Honda', value: 'honda'}
];
const modelsByMake = {
ford: [
{text: 'Explorer', value: 'explorer'},
{text: 'Expedition', value: 'expedition'}
],
honda: [
{text: 'Civic', value: 'civic'},
{text: 'Accord', value: 'accord'}
]
};
const sel2 = $('#select2').selectize({
options: models,
items: [''],
valueField: 'value',
labelField: 'text',
sortField: 'value',
searchField: ['text'],
load: (query, callback) => {
let options = [];
$.each(modelsByMake, (i, v) => {
options = options.concat(v);
});
callback(options);
},
preload: true
});
const sel1 = $('#select1').selectize({
options: makes,
items: [''],
valueField: 'value',
labelField: 'text',
sortField: 'value',
searchField: ['text'],
onChange: (value) => {
let options = models;
if (value) {
// get models for selected make
options = options.concat(modelsByMake[value]);
} else {
// get all models
$.each(modelsByMake, (i, v) => {
options = options.concat(v);
});
}
sel2[0].selectize.clear(); // clear sel2 selected items
sel2[0].selectize.clearOptions(); // clear sel2 options
// load options corresponding to sel1 value in sel2
sel2[0].selectize.load((callback) => {
callback(options);
});
// refresh sel2 options list
sel2[0].selectize.refreshOptions();
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Selectize</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.default.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.js"></script>
</head>
<body>
<select id="select1"></select>
<select id="select2"></select>
</body>
</html>

Related

Gettin the value from a selected option in Selectize.js

I am using multiselect in selectize.js, how do i get the vales from the select options:
html:
<div class="selectBox1" multiple="multiple">
<select id="period">
<option value="day">Day</option>
<option value="week">Week</option>
<option value="month">Month</option>
<option value="year">Year</option>
</select>
select.js init:
$(document).ready(function($){
$('#period').selectize({
sortField: "text",
placeholder: "Select a Period..",
});
});
I tried to get the value by simply using this code:
var values = $('#period').val();
console.log(values)
but it returns an empty array.
what can i do?
Just add onChange handler:
$(document).ready(function($){
$('#period').selectize({
sortField: "text",
placeholder: "Select a Period..",
onChange(value) {
console.log(value);
}
});
});

angular js ng-option not working for select tag

I'm trying to get the ng-option to use a JSON formatted array, but not sure why it's not displaying the select option rows. For instance:
index.js:
$scope.seloptions= [{ key: k1, name: n1 },{ key: k2, name: n2 }];
index.html:
<select name="set_aside" ng-model="set_aside" ng-options="option.key for option in seloptions track by name"></select>
I have no idea what I'm doing wrong. The select tag is not getting populated.
EDIT
Also assume that the necessary setup for the angular code is there and both files are in same directory.
The problem is that you are tracking by name which is undefined.
update line :
ng-options="option.key for option in seloptions track by name"
to
ng-options="option.key for option in seloptions track by option.name"
Working example :
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.seloptions= [{ key: "key1", name: "n1" },{ key:" key2", name: "n2" }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="plunker">
<div ng-controller="MainCtrl">
<select name="set_aside" ng-model="set_aside" ng-options="option.key for option in seloptions track by option.name">
<option value="">Select One</option>
</select>
</div>
</body>

Rebind DropDownList to value field after filtering

After filtering then unfiltering a kendo dropdownlist, the view model retains the originally selected value, but the dropdownlist has an empty string for its value.
Is this expected behavior for the dropdownlist? I'd expect the widget to stay in sync with its model. How can I "rebind" the dropdownlist, so it gets the value from its view model after filtering?
var viewModel = kendo.observable({
selectedProduct: null,
products: [
{ id: 1, name: "Coffee" },
{ id: 2, name: "Tea" },
{ id: 3, name: "Juice" }
]
});
kendo.bind($("#dropdown"), viewModel);
var ddl = $("#dropdown").getKendoDropDownList();
console.log("viewModel.selectedProduct.id: " + viewModel.selectedProduct.id + ", ddl.value(): " + ddl.value());
ddl.dataSource.filter({field: "id", value: 4});
ddl.dataSource.filter({});
console.log("viewModel.selectedProduct.id: " + viewModel.selectedProduct.id + ", ddl.value(): " + ddl.value());
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<link href="http://cdn.kendostatic.com/2015.2.624/styles/kendo.common.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2015.2.624/styles/kendo.default.min.css" rel="stylesheet" />
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.2.624/js/kendo.all.min.js"></script>
</head>
<body>
<select id="dropdown" data-role="dropdownlist" data-option-label="Select product..."
data-value-field="id" data-text-field="name" data-bind="value: selectedProduct, source: products">
</select>
<script>
</script>
</body>
</html>
Here's how I was able to rebind the value. It depends on some undocumented Kendo stuff though, so I'd still prefer another way.
var binding = ddl.element.get(0).kendoBindingTarget.toDestroy[0].bindings.value;
var value = binding.source.get(binding.path);
if (value) {
ddl.value(value.get(ddl.options.dataValueField));
}

Change or Focus in jQuery? Which event should I use with select dropdown to give a call to jQuery-AJAX function?

I've one select dropdown control in HTML as follows :
<select id="student" name="student" class="form-control"></select>
I want to call a jQuery-AJAX function which will add the option values to the above HTML select control.
Following is the code for I've written for it:
$.ajax({
url : "http://google.com",
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
'op':'get_all_students'
},
success: function(result, success) {
$('#student').html(result);
},
error: function() {
alert("Error is occured");
}
});
My issue is on which event of HTML select dropdown should I call the above jQuery-AJAX function in order to add the option values dynamically?
Please suggest me the proper way to do this.
on page load is a good option.
jQuery(function($) {
// Ajax call populate select options
$.ajax({ /* ... */ });
});
if it depends on other selected elements, then bind change event on first dropdownlist
e.g. nested dropdown list
<select id="teacher" name="teacher" class="form-control">
<option value="">Please select</option>
<option value="1">Teacher 1</option>
<option value="2">Teacher 2</option>
</select>
<select id="student" name="student" class="form-control"></select>
<script type="text/javascript">
jQuery(function($) {
$("#teacher").on('change', function() {
// Ajax call populate select options
$.ajax({ /* ... */ });
});
});
</script>
Listen for change event on select and then create the the dynamic <option> elements poulating the #student element with them:
var data = {
1: [{name: "Alice", id: 1}, {name: "Bob", id: 2}],
2: [{name: "Carol", id: 2}, {name: "Dave", id: 3}]
};
function getStudents() {
var result = data[$("#school").val()];
var $options = [];
$.each(result, function (i, c) {
var $opt = $("<option>");
$opt.attr({
value: c.id
}).text(c.name);
$options.push($opt);
});
$("#students").append($options);
}
$("#school").on("change", getStudents);
getStudents();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="school">
<option value="1">School 1</option>
<option value="2">School 2</option>
</select>
<select id="students"></select>

Drop down not getting displayed

Problem Question -
I have a two drop down in my view. And second drop down rely on the first one. But somehow second one does not get updated
// my firstdrop down
<select ng-controller="myController"
ng-options="customer.name for customer in customerDetailData" ng-model="customer"
ng-change="updateCost(customer)">
<option value="">Please select customer</option>
</select>
// my second drop down
<select ng-controller="myController"
ng-options="cc.name for cc in customerCostData">
<option value="">Please select cost</option>
</select>
// my controller
(function() {
var myController = function($scope,Service){
$scope.customerDetailData;
Service.cust()
.success(function(data){
console.log(data)
$scope.customerDetailData = data;
})
.error(function(status,error){
})
$scope.customerCostData;
$scope.updateCost=function(customer){
Service.cost(customer.id)
.success(function(cost){
$scope.customerCostData= cost
})
.error(function(status,data){
console.log(status);
console.log(data);
})
}
};
myController .$inject = ['$scope','Service'];
angular.module('app').controller('myController ',myController );
}());
Is anything i am missing ? the data is coming through fine in the console. Please guide me
There are 2 things to do here:
The first and main issue is that you are attaching ng-controller to each select individually. This means it is actually creating 2 separate controllers, one for each select, and so they are given different scopes. You need to apply the ng-controller attribute to a parent element, such as the form.
The second issue is that angular will not automatically update an element just because the scope variable is used in ng-options. You therefore need to give it a ng-model so that Angular watches it correctly.
Here is an example of the code with two separate controller instances. Note the 2 alerts:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<form ng-app="myApp">
<select ng-controller="myController"
ng-options="customer.name for customer in customerDetailData" ng-model="customer"
ng-change="updateCost(customer)">
<option value="">Please select customer</option>
</select>
<select ng-controller="myController"
ng-options="cc.name for cc in customerCostData" ng-model="customercustomerCostData">
<option value="">Please select cost</option>
</select>
</form>
<script type="text/javascript">
(function () {
var myApp = angular.module('myApp', []);
var myController = function ($scope) {
alert('myController created');
$scope.customerDetailData = [{ id: 1, name: "bob" }, { id: 2, name: "fred" }];
$scope.updateCost = function (customer) {
$scope.customerCostData = [{ name: customer.id.toString() }, { name: 'x' }];
}
};
myController.$inject = ['$scope'];
myApp.controller('myController', myController);
}());
</script>
Here it is with the single ng-controller applied to the form and ng-model="customerCostData" on the second select, so it now works:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<form ng-app="myApp" ng-controller="myController">
<select
ng-options="customer.name for customer in customerDetailData" ng-model="customer"
ng-change="updateCost(customer)">
<option value="">Please select customer</option>
</select>
<select
ng-options="cc.name for cc in customerCostData" ng-model="customercustomerCostData">
<option value="">Please select cost</option>
</select>
</form>
<script type="text/javascript">
(function () {
var myApp = angular.module('myApp', []);
var myController = function ($scope) {
alert('myController created');
$scope.customerDetailData = [{ id: 1, name: "bob" }, { id: 2, name: "fred" }];
$scope.updateCost = function (customer) {
// would be an ajax call
$scope.customerCostData = [{ name: customer.id.toString() }, { name: 'x' }];
}
};
myController.$inject = ['$scope'];
myApp.controller('myController', myController);
}());
</script>
is the cost data the result of an Ajax request? if so, you may need to force a force a $digest cycle to let the UI know the model has been changed. You can achieve this by wrapping the assignment of cost in a $timeout, or $apply.
$timeout(function () {
$scope.customerCostData = cost;
});
or
$scope.$apply(function () {
$scope.customerCostData = cost;
});

Categories