I am using https://github.com/localytics/angular-chosen to allow for select tags with search capability for many options.
The problem I'm having is with preselecting an option on an already saved vendor object. When creating a new one there is now issue, but if we're viewing an existing vendor, I want to show the vendor's name in the select box, rather than the placeholder.
<select chosen
ng-model="myVendor"
ng-options="vendor['public-id'] as vendor.name for vendor in vendors"
data-placeholder="Nah">
</select>
And in my controller, I'm setting the model by hand $scope.myVendor = "Some value"
The problem is that I'm populating the options with an object, instead of a key/value. I found an example of it working with a key/value, but haven't had success adapting this to objects as options.
I've even tried setting myVendor to the matching object that I want selected, with no luck.
Plunker of issue
I updated the plunker and change my previous changes on the plugin. this was not the issue. I don't understand how it was giving me errors there.
The solution is to track with an object and two functions the id and the name:
// Controller
$scope.vendors = [
{
"public-id": "1234",
"name": "stugg"
},
{
"public-id": "4321",
"name": "pugg"
}
];
$scope.myVendor = {name: "pugg", id:""};
$scope.updateMyVendorName = function () {
var found = false,
i = 0;
while (!found && i < $scope.vendors.length) {
found = $scope.vendors[i]['public-id'] === $scope.myVendor.id;
if (found) {
$scope.myVendor.name = $scope.vendors[i].name;
}
i++;
}
}
findVendorByName();
function findVendorByName () {
var found = false,
i = 0;
while (!found && i < $scope.vendors.length) {
found = $scope.vendors[i]['name'] === $scope.myVendor.name;
if (found) {
$scope.myVendor.id = $scope.vendors[i]['public-id'];
}
i++;
}
}
// template
<select chosen class="form-control span6" ng-options="vendor['public-id'] as vendor.name for vendor in vendors" ng-model="myVendor.id" ng-change="updateMyVendorName()">
{{myVendor.name}}
Related
enter image description hereWhat I'm trying is fetching columns from the user to which the user entered, The Good thing is Columns are getting fetched and the bad thing is the columns that I had applied conditions are not working.Can anyone help me out? I want a query that works for the filter option as in many websites to filter any product or something.
Newbie here!!!
routes.post('/FilterCandidate',function(req,res){
var fetchparameter={};
var dynamicquery={author : req.user.username};
if(req.user.username){
if(req.body.ConsultantName){
fetchparameter["ConsultantName"] = req.body.ConsultantName;
}
if(req.body.Location){
fetchparameter["Location"] = req.body.Location;
}
if(req.body.JobRole){
fetchparameter["JobRole"] = req.body.JobRole;
}
if(req.body.Skills){
fetchparameter["Skills"] = req.body.Skills.split(',');
}
if(req.body.VisaStatus){
fetchparameter["VisaStatus"] = req.body.VisaStatus;
}
if(req.body.BillingRate){
fetchparameter["BillingRate"] = req.body.BillingRate;
}
if(req.body.experience){
fetchparameter["experience"] = req.body.experience;
}
if(req.body.jobtype){
fetchparameter["jobtype"] = req.body.jobtype;
}
if(req.body.Availability){
fetchparameter["Availability"] = req.body.Availability;
}
if(req.body.experience){
fetchparameter["Salary"] = req.body.Salary;
}
if(req.body.Salarytype){
fetchparameter["Salarytype"] = req.body.Salarytype;
}
}
/* This below code for conditions is not working*/
for(var key in fetchparameter){
if (key== "Salary" ){
dynamicquery[key] = {$gte :fetchparameter[key]};
}
if(key == "Skills"){
dynamicquery [key] = {$in : fetchparameter[key]};
}
if(key == "experience"){
dynamicquery[key] = {$gte :fetchparameter[key]};
}
else{
dynamicquery[key] = fetchparameter[key];
}
}
console.log(dynamicquery);
Candidate.aggregate([ {$match : dynamicquery }],(err,docs) =>{
res.render('FilteredCandidate',{'Candidates' : docs});
});
});
This is what I'm getting output to refer to the attached image
i think you should make a match object array it will make your code more neat and hoping that it will solve your problem
Ex:
var match = {$and:[]};
if(any condition satisfy){
match.$and.push({}) //condition
}
and most important do check if match.$and array must not be empty if it is then delete match.$and. this procedure will help you to maintain your query better provides more flexibility.
I have a table categories and a documents. I want to create a new document and associate this document with a category already created.
The category table has the title field.
In the document creation form I want to put the categories already created in a select.
I tried doing this in the code below, but I ended up getting the select a key from the category -L0_xe_FIK9QdfTGhBDG for example, but I wanted the category title.
var documentosRef = firebase.database().ref('documentos');
var categoriasRef = firebase.database().ref('categorias');
var keyDocumento = ""
function initFirebase(){
categoriasRef.on('value', function(data) {
$('#categoria').html('');
for(categoria in data.val()){
option = "<option>"+categoria+"</option>"
$('#categoria').html($('#categoria').html()+option);
}
})
}
Structure:
{ "categorias": {
"L0_xe_FIK9QdfTGhBDG": {
"titulo": "Categorias 1"
},
"-L0a0FPFkXkKb3VNFN0c":{
"titulo": "Categorias 2"
}
}
Let check it out: JavaScript for/in Statement
var categorias = data.val();
for(var key in categorias){
option = "<option>"+categorias[key].titulo +"</option>"
$('#categoria').html($('#categoria').html()+option);
}
I am trying to set selected option for the select menu but its not working because data that I am sending to ng-model has different $$hashKey from data in the select menu and $$hashKey holding for values.
<select class="form-control" ng-model="selManga" ng-options="manga.seri for manga in mangalar">
<option value="">Manga Seçin</option>
</select>
<select ng-change="selPage = 0" ng-model="selChapter" ng-options="selManga.randomword.indexOf(chapter) as chapter.klasor for chapter in selManga.randomword">
<option value="">Bölüm</option>
</select>
<select ng-model="selPage" ng-options="selManga.randomword[selChapter].yol.indexOf(page) as selManga.randomword[selChapter].yol.indexOf(page) + 1 for page in selManga.randomword[selChapter].yol">
</select>
I google it to get around with this people says track by but I have to use as. So is there a another way to get around it?
Selected value for first select menu is working but second one is not working. Here is plunker.http://plnkr.co/edit/3V8JSF2AU01ZZNPfLECd?p=info
.controller('nbgCtrl',function ($scope, MMG, $stateParams) {
var milo = $stateParams.serix;
var musti = $stateParams.klasor;
MMG.adlar.success(function(loHemen) {
var i, miloMangaInArray;
for (i=0; i<loHemen.length; i++) {
if (loHemen[i].seri===milo) {
miloMangaInArray = loHemen[i];
break;
}
};
var a;
for (a=0; a<miloMangaInArray.randomword.length; a++) {
if(miloMangaInArray.randomword[a].klasor===musti) {
break;
}
}
$scope.mangalar = loHemen; //JSON Data
$scope.selManga = $scope.mangalar[i]; // First select menu's ng-model and its working.
$scope.selChapter = $scope.mangalar[i].randomword[a]; //Second select menu's ng-model and its not working due to no matching JSON data.
});
$scope.next = function (manga, chapter, page) {
var nextPage = page + 1;
if (angular.isDefined(manga.randomword[chapter].yol[nextPage])) {
$scope.selPage = nextPage;
} else if (angular.isDefined(manga.randomword[chapter + 1])) {
$scope.selChapter = chapter + 1;
$scope.selPage = 0;
}};
})
Dude here you go, a js fiddle for the solution
http://jsfiddle.net/yw248mfu/2/
the method I used here is indexOf to get the index of the page in the array for the last select only ,,
and this is not the best solution as it will have to apply index of every time the digest loop run ,,
I can think of a number of different solutions to this ,,
1- you can extract the id of the page from the name of the image itself
2- you can map the pages array to be a list of objects with the following schema
[{"index":1,"img":"00.jpg"},{"index":2,"img":"01.jpg"},{"index":3,"img":"02.jpg"}]
you can do the second option with this piece of code
pages.map(function(d,i){return {"index":i,"img":d};});
crouch74
I think you should embrace the AngularJS way of handling models and bindings. So, instead of keeping track of all the different indexes through your view code, you can simply let ng-select assign references to parts of your model (via ng-model). By changing the HTML and controller slightly, you can simplify some of the code, and it will actually work, too.
First, make a shared $scope.model = {…} object available on the $scope. Then, change the HTML to
<select ng-model="model.selManga" ng-options="manga.seri for manga in mangalar">
<option value="">Manga Seçin</option>
</select>
<select ng-model="model.selChapter" ng-options="chapter.klasor for chapter in model.selManga.randomword" ng-change="model.selPage = model.selChapter.yol[0]">
<option value="">Bölüm</option>
</select>
<select ng-model="model.selPage" ng-options="page as model.selChapter.yol.indexOf(page) + 1 for page in model.selChapter.yol">
</select>
<img class="picture" ng-src="http://baskimerkeziankara.com/{{model.selPage}}" ng-click="next(model.selPage)">
After that, change the controller is changed accordingly:
.controller('nbgCtrl', function($scope, MMG, $stateParams) {
var model = {
selManga: undefined,
selChapter: undefined,
selPage: undefined
};
$scope.model = model;
MMG.adlar.success(function _init(loHemen) {
for (var i = 0; i < loHemen.length; i++) {
if (loHemen[i].seri === $stateParams.serix) {
model.selManga = loHemen[i];
break;
}
}
for (var a = 0; a < model.selManga.randomword.length; a++) {
if (model.selManga.randomword[a].klasor === $stateParams.klasor) {
model.selChapter = model.selManga.randomword[a];
break;
}
}
model.selPage = model.selChapter.yol[0];
$scope.mangalar = loHemen;
});
$scope.next = function _next(page) {
var pageIndex = model.selChapter.yol.indexOf(page);
if (angular.isDefined(model.selChapter.yol[pageIndex + 1])) {
model.selPage = model.selChapter.yol[pageIndex + 1];
} else {
var chapterIndex = model.selManga.randomword.indexOf(model.selChapter);
if (angular.isDefined(model.selManga.randomword[chapterIndex])) {
pageIndex = 0;
model.selChapter = model.selManga.randomword[chapterIndex + 1];
model.selPage = model.selChapter.yol[pageIndex];
}
}
console.log('manga', model.selManga.seri,
'chapter', model.selChapter.klasor,
'selPage', pageIndex + 1);
};
})
I've created a forked Plunker that shows how this works (and this solution actually works): http://plnkr.co/edit/2aqCUAFUwwXuGQHpuooj
Alright, so I'm trying to use select2's tagging and AJAX functionality in conjunction for my categories selection.
Currently, the user can search for categories to add to their post. One nice thing I noticed is that, select2 won't let you select the same selection twice (it's grayed and nothing happens when you click on it).
Here's my challenge... let's say a user is editing a post and already has categories selected. These categories appear below the select2 search. For example, let's say the user has the category "Life" selected. This will appear below already checked off.
The problem arises though, when the user searches for "Life". They'll be able to select it and add it again. I could just parse the previous selections and negate the selection, but I'd really like to use the built in functionality of select2 for the sake of consistency.
So how do I set incoming AJAX results to be already selected so that they can't be selected again?
Here's a fiddle. Notice how "Experiences" is grayed out when you search for it, but "life" is not even though it's already selected.
http://jsfiddle.net/odLnznct/1/
function formatStuff(stuff) {
if (stuff.loading) return 'Searching...';
markup = "<p>" + stuff.text + "</p>";
return markup;
}
function formatRepoSelection(stuff) {
return stuff.cat_name || $('.js-select').val();
}
function catAdd() {
var addCat = div = clo = label = labelText = null;
cat = $('.js-select').select2('data');
addCat = cat[0].text;
div = $('#categories-cat_name div.checkbox:first');
clo = div.clone();
$('input[type="checkbox"]', clo).val(addCat);
label = $('label', clo);
labelText = label[0].childNodes[label[0].childNodes.length - 1];
labelText.textContent = addCat;
$(div).before(clo);
}
$('.js-select').select2({
tags: true,
ajax: {
url: 'https://api.myjson.com/bins/58uwe',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term
};
},
processResults: function (data, page) {
var select2Data = $.map(data, function (obj) {
obj.id = obj.cat_id;
obj.text = obj.cat_name;
return obj;
});
return {
results: select2Data
};
},
cache: true
},
escapeMarkup: function (markup) {
return markup;
},
minimumInputLength: 1,
templateResult: formatStuff,
templateSelection: formatRepoSelection
});
$('.js-select').on('select2:select', function () {
catAdd();
});
You can try this.
Since your results could be multiple, you need to set your select element's multiple true to enable it and just add selected option as default value.
You can do it either javascript or html.
<div id='select-test'>
<select class="js-select" style="width:90%;" multiple=true>
<option value="Life" selected=true>Life</option>
<option value="Joy" selected=true>Joy</option>
</select>
</div>
I use bootstrap multi-select and I want to update options on flow with ajax
To populate on init my multiselect I do
<select name="model" class="multiselect" multiple="multiple">
<? foreach ($sel_models as $mod) { ?>
<option value="<?= $mod ?>" <?= ($mod == $params['model']) ? 'selected' : '' ?>><?= $mod ?></option>
<? } ?>
</select>
then on event I would like to update my option list with the following ajax
I was trying to use the rebuild method but won't fire the drop-down after creation
$.ajax({
type: 'post',
url: "helper/ajax_search.php",
data: {models: decodeURIComponent(brands)},
dataType: 'json',
success: function(data) {
$('select.multiselect').empty();
$('select.multiselect').append(
$('<option></option>')
.text('alle')
.val('alle')
);
$.each(data, function(index, html) {
$('select.multiselect').append(
$('<option></option>')
.text(html.name)
.val(html.name)
);
});
$('.multiselect').multiselect('rebuild')
},
error: function(error) {
console.log("Error:");
console.log(error);
}
});
With firebug I can see that the list is generated but on select won't show up
In the doc I can read :
.multiselect('setOptions', options)
Used to change configuration after initializing the multiselect. This may be useful in combination with .multiselect('rebuild').
Maybe you can't change your widget data by your initial way. In a correct way you should use setOptions method.
Else : With your way, maybe should you think about destroy your widget .multiselect('destroy') and create it again after.
Update after comment :
In the doc : ( you've linked )
Provides data for building the select's options the following way:
var data = [
{label: "ACNP", value: "ACNP"},
{label: "test", value: "test"}
];
$("#multiselect").multiselect('dataprovider', data);
So :
When you get data from your ajax call, you have to create an array of objects ( it's the options in the select you want to have ) with the format like
var data =
[
{label: 'option1Label', value: 'option1Value'},
{label: 'option2Label', value: 'option2Value'},
...
]
When your objects array is created, then you just have to call the method
$("#multiselect").multiselect('dataprovider', data);
Where data is your array of objects.
I hope I'm clear :/
As an alternative to multiselect('dataprovider', data) you can build the list with jquery append exactly the way you did in your question. The only change you need to make is to delay the rebuild until after the ajax request is complete.
var buildDrivers = $.getJSON('resources/orders/drivers.json', function(data) {
$.each(data, function(i, driver) {
$('#toolbar select[name="drivers"]').append('<option>'+driver+'</option>');
});
});
buildDrivers.complete(function() {
$('.multiselect').multiselect('rebuild');
});
see http://api.jquery.com/jquery.getjson/ for documentation
I've been added the functionality of updating options after filtering and getting them from the server side. This solution relays on the concept of injecting new options, destroying the select and initializing it again.
I took into account:
Considering the existing selected options, which must stay.
Removing duplicate options (might be as a conflict from which that already selected and the new that came from the server).
Keeping the options tray open after the update.
Reassign the previous text in the search text box & focusing it.
Just add the 'updateOptions' as a function after the 'refresh' function along with the two helper functions as follows:
updateOptions: function (options) {
var select = this.$select;
options += this.getSelectedOptionsString();
var selectedIds = select.val(),
btnGroup = select.next('.btn-group'),
searchInput = btnGroup.find('.multiselect-search'),
inputVal = searchInput.val();
options = this.removeOptionsDuplications(options);
if (!options) {
options = '<option disabled></option>';
}
// 1) Replacing the options with new & already selected options
select.html(options);
// 2) Destroyng the select
select.multiselect('destroy');
// 3) Reselecting the previously selected values
if (selectedIds) {
select.val(selectedIds);
}
// 4) Initialize the select again after destroying it
select.multiselect(this.options);
btnGroup = select.next('.btn-group');
searchInput = btnGroup.find('.multiselect-search');
// 5) Keep the tray options open
btnGroup.addClass('open');
// 6) Setting the search input again & focusing it
searchInput.val(inputVal);
searchInput.focus();
},
getSelectedOptionsString: function () { // Helper
var result = '',
select = this.$select,
options = select.find('option:selected');
if (options && options.length) {
$.each(options, function (index, value) {
if (value) {
result += value.outerHTML;
}
});
}
return result;
},
removeOptionsDuplications: function (options) { // Helper
var result = '',
ids = new Object();
if (options && options.length) {
options = $(options);
$.each(options, function (index, value) {
var option = $(value),
optionId = option.attr('value');
if (optionId) {
if (!ids[optionId]) {
result += option[0].outerHTML;
ids[optionId] = true;
}
}
});
}
return result;
},
Demo:
State:
"Option 1"
$('#select').multiselect('updateOptions', '<option value="2">Option 2</option>');
State:
"Option 2"
"Option 1"
I think this is an easier way to add options on the fly (using ajax or any other listener) to an existing Bootstrap MultiSelect.
Following is a simplified example to add options:
function addOptionToMultiSelect(multiselectSelector, value, selected) {
var data = [];
$(multiselectSelector + ' option').each(function(){
var value = $(this)[0].value;
var selected = $(this)[0].selected;
data.push({label: value, value: value, selected: selected});
});
// Add the new item
data.push({label: value, value: value, selected: selected});
$(multiselectSelector).multiselect('dataprovider', data);
}
For simplicity, I have assumed both the label and value are the same in an option. Note that the already selected options are taken care of by reading the selected attribute from the existing options. You can make it more sophisticated by tracking the disabled and other attributes.
Sample:
addOptionToMultiSelect('#multiselect-example', 'new-option', true);