selectize.js dynamically adding options to select - selectize.js

I am trying to use selectize.js library. On document.ready i make a ajax call and get the options to add into select list.
Here is the html for select tag
<select id="select-country-field" name="country-field-list[]" multiple class="demo-default" style="width:50%" placeholder="Select a state...">
<option value="">Select ...</option>
</select>
and here is how I add options on $(document).ready
var $select = $(document.getElementById('select-country-field')).selectize(options);
var selectize = $select[0].selectize;
selectize.addOption({value:1,text:'foo'});
selectize.addItem(1);
selectize.refreshOptions();
I looked at the following question asked but that did not get it to work
Selectize.js manually add some items
Any help?

You can just move your ajax call into selectize load method like that:
$('#select-country-field').selectize({
valueField: 'country',
labelField: 'country',
searchField: 'country',
options: [],
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: 'http:// ajax-call-url',
type: 'GET',
dataType: 'json',
data: {
country: query,
},
error: function() {
callback();
},
success: function(res) {
callback(res);
}
});
}
});
'http:// ajax-call-url' should return array like that:
[{ country: 'USA'}, {country: 'GB'}, {country: 'FR'}, ... ]

Related

Vuejs- How to show name values in a <v-select> but send the ID in the axios POST request

EDIT: I fixed it by adding the return-object prop to v-select
When I add a student to a database from a vuetify form, I want to be able to assign them a course. But the course has to be in a list of available courses (also in the db). I managed to do that and show all the available courses in a dropdown menu.
However, when I add the new student to the database, it sends the name of the course but not the ID of the course, so the database doesn't recognize it. I would like to link the name of the course from the v-select dropdown menu to its object ID and send the ID in the POST request.
My form component:
<v-select
:items="courses"
v-model="Courses"
item-value="name"
item-text="name"
label="Available courses"
prepend-icon="folder"
>
<template v-slot:item="{ item, attrs, on }">
<v-list-item
v-bind="attrs"
v-on="on"
>
<v-list-item-title
:id="attrs['aria-labelledby']"
v-text="item.name"
></v-list-item-title>
</v-list-item>
</template>
</v-select>
Where I store all the available courses:
computed: {
courses() {
return this.$store.state.courses;
},
The axios POST method:
methods: {
async addItem(){
const response = await axios.post("http://localhost:4000/api/student", {
name: this.name,
Courses: this.courses,
});
this.items.push(response.data);
this.name = "";
this.courses ="";
},
},
My mongoDB model:
const Student = mongoose.model(
"Student",
new mongoose.Schema({
name: String ,
Courses:
{
type: mongoose.Schema.Types.ObjectId,
ref:"id"
},
})
);
module.exports = Student;
The Course model:
const Course = mongoose.model(
"Course",
new mongoose.Schema({
name: String ,
available: {type:Boolean , default :true} ,
})
);
module.exports = Course;
Need more information on how each course object looks, and your data, but essentially, set the item-value prop to the item's object ID, and under the addItem function,
async addItem(){
const response = await axios.post("http://localhost:4000/api/student", {
id: this.courseId,
Courses: this.courses,
});
this.items.push(response.data);
this.courseId = "";
this.courses ="";
}
EDIT:
It might be a good idea to name your variables better, e.g.
// in your v-select
v-model="selectedCourse"
// in your addItem function
Course: this.selectedCourse
or
Courses: this.selectedCourses
If you just want to get id of the course in v-model of v-select, You can simply use item-value="id" instead of item-value="name".
Live Demo :
new Vue({
el: '#app',
vuetify: new Vuetify(),
data: () => ({
selectedCourse: null,
courses: [{
id: 1,
name: 'Course 1'
}, {
id: 2,
name: 'Course 2'
}, {
id: 3,
name: 'Course 3'
}, {
id: 4,
name: 'Course 4'
}, {
id: 5,
name: 'Course 5'
}],
}),
methods: {
getSelected() {
console.log(this.selectedCourse) // ID of the selected course
}
}
})
<script src="https://unpkg.com/vue#2.x/dist/vue.js"></script>
<script src="https://unpkg.com/vuetify#2.6.6/dist/vuetify.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/vuetify#2.6.6/dist/vuetify.min.css"/>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Material+Icons"/>
<div id="app">
<v-app id="inspire">
<v-container fluid>
<v-select
:items="courses"
v-model="selectedCourse"
label="Available courses"
prepend-icon="folder"
item-value="id"
item-text="name"
#change="getSelected"
></v-select>
</v-container>
</v-app>
</div>

What is the ideal way to display a datatable inside a YUI View

Given a YUI app with two views, HomePageView & tradedeskPageView, I want to display a datatable in the tradedeskview. TradedeskView is defined with a template like,
<script id="t-tradedesk" type="text/x-handlebars-template">
<div id="my-datatable"></div>
</script>
And the view is defined as below,
YUI().add('tradedeskPageView', function(Y) {
Y.TradedeskPageView = Y.Base.create('tradedeskPageView', Y.View, [], {
// Compiles the tradedeskTemplate into a reusable Handlebars template.
template: Y.Handlebars.compile(Y.one('#t-tradedesk').getHTML()),
initializer: function () {
var cols = [
{ key: 'id', label: 'ID' },
{ key: 'name', label: 'Name' }
];
var data = [
{ id: 12345, name: 'Srikanth'},
{ id: 12346, name: 'Aditya'}
];
this.table = new Y.DataTable({
columns: cols,
data: data
});
//this.table.render('#my-datatable'); This is not possible as view is not rendered and node with given id wont exist
},
render: function () {
var content = this.template();
this.get('container').setHTML(content);
return this;
}
});
}, '1.0.0', {
requires: []
});
How should I render table in the required div i.e., #my-datatable in this case.
Give this a go:
render: function () {
var content = this.template(),
container = this.get('container');
container.setHTML(content);
this.table.render(container.one('#my-datatable')); //node exists at this point
return this;
}
You can init the DataTable in you view's initializer, but only render it when the View itself is rendered

Select User stories based on feature using Rally API

I'm trying to fetch all user stories that belong to certain feature, but which have children.
Here's how I created query for that using rally-node.
async.map(features, function(feature, cb) {
self.restApi.query({
type: 'hierarchicalrequirement',
limit: Infinity,
order: 'Rank',
fetch: ['FormattedID', 'Name', 'Children'],
parent: feature.ObjectID,
query: queryUtils.where('DirectChildrenCount', '>', 0)
}, cb);
}, function(err, results) {
//user stories
});
And here's how my feature looks like:
{ _rallyAPIMajor: '2',
_rallyAPIMinor: '0',
_ref: 'https://rally1.rallydev.com/slm/webservice/v2.0/portfolioitem/feature/18846103932',
_refObjectUUID: 'c01d7f828-a6d6-4efc-8160-c0c19ad0fabc',
_objectVersion: '7',
_refObjectName: 'Dashboard Widgets',
ObjectID: 18836103932,
FormattedID: 'F1',
DirectChildrenCount: 2,
Name: 'Dashboard Widgets',
UserStories:
{ _rallyAPIMajor: '2',
_rallyAPIMinor: '0',
_ref: 'https://rally1.rallydev.com/slm/webservice/v2.0/PortfolioItem/Feature/18846103932/UserStories',
_type: 'HierarchicalRequirement',
Count: 2 },
_type: 'PortfolioItem/Feature' },
I'm new to rally, so any further help regardind documentation, etc, is really appreciated.
Here is a full example where Feature is queried and its UserStories collection is fetched and then hydrated.
v2.0 removed the ability to return child collections in the same response for performance reasons. Now fetching a collection will return an object with the count and the url from which to get the collection data. Separate request is needed to hydrate a collection.
This change is documented here
I do not see a question in your post, I am not sure what problem you encounter, but his code gets user stories based on feature, filtered by ('DirectChildrenCount', '>', 0)
var rally = require('rally'),
queryUtils = rally.util.query;
mySettings = {
apiKey: '_secret',
server: 'https://rally1.rallydev.com', //this is the default and may be omitted
requestOptions: {
headers: {
'X-RallyIntegrationName': 'My cool node.js program',
'X-RallyIntegrationVendor': 'My company',
'X-RallyIntegrationVersion': '1.0'
},
}
},
restApi = rally(mySettings);
function queryFeature() {
return restApi.query({
type: 'portfolioitem/feature',
fetch: ['FormattedID', 'Name', 'UserStories'],
query: queryUtils.where('FormattedID', '=', 'F7')
});
}
function queryChildren(result) {
return restApi.query({
ref: result.Results[0].UserStories,
limit: Infinity,
order: 'Rank',
fetch: ['FormattedID', 'Name'],
query: queryUtils.where('DirectChildrenCount', '>', 0)
});
}
function onSuccess(result) {
console.log('Success!', result);
}
function onError(errors) {
console.log('Failure!', errors);
}
queryFeature()
.then(queryChildren)
.then(onSuccess)
.fail(onError);

Create search articles feature in MEAN stack

First of all, let me tell you that I'm a novice in the world of javascript and node.js. I have been searching for help in trying to do what i want but haven't found yet.
I am using the MEAN stack(http://mean.io/) and I am trying to implement a search feature in the included articles model. The search would look for articles with a specific tag and would be implemented in the index page. Follow me and see if you can find what I am missing please.
In the backend:
app/models/
/**
* Article Schema
*/
var ArticleSchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true
},
content: {
type: String,
default: '',
trim: true
},
tag: {
type: String,
default: '',
trim: true
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
app/controllers/
exports.searcharticle = function(req, res) {
Article.find({'tag': req.params.tag}).sort('-created').populate('user', 'name username').exec(function(err, articles) {
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(articles);
}
});
};
Added the route for the search in app/routes/articles.js
app.get('/articles/search/:tag', articles.searcharticle);
In the frontend:
Created the view for the search wich will display the search results - public/views/articles/search.html
<section data-ng-controller="ArticlesController" data-ng-init="searchart()">
<ul class="articles unstyled">
<li data-ng-repeat="article in articles">
<span>{{article.created | date:'medium'}}</span> /
<span>{{article.user.name}}</span>
<h2><a data-ng-href="#!/articles/{{article._id}}">{{article.name}}</a></h2>
<div>{{article.tag}}</div>
</li>
</ul>
<h1 data-ng-hide="!articles || articles.length">Your search hasn't returned any results. <br> Why don't you Create One?</h1>
</section>
The view for the index.html, where the searchbox will be implemented
<section data-ng-controller="ArticlesController">
<form role="form" data-ng-submit="searchart()">
<div>
<div>
<input type="text" id="tag" ng-model="selected" class="form-control" placeholder="Tag">
</div>
<div>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
Added the route to the config.js
when('/articles/search/:tag', {
templateUrl: 'views/articles/search.html'
}).
And added the search function to the articles controller
$scope.searchart = function() {
Articles.query(function(articles) {
$scope.articles = articles;
});
};
Right now, with this code implemented, when I click in the submit button in the index page, nothing happens.
Can you find what am I missing?
Thanks in advance!
In order to use a URL in your client Article Service, you should define the URL Parameter in the articles service at: packages/articles/public/services/article.js, like the articleId parameter already defined in there like this:
angular.module('mean.articles').factory('Articles', ['$resource',
function($resource) {
return $resource('articles/:articleId', {
articleId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
Then you need to pass it in your angular controller search method, like the function that gets one by id, like this:
$scope.findOne = function() {
Articles.get({
articleId: $stateParams.articleId
}, function(article) {
$scope.article = article;
});
};
Personally I don't know how to add another parameter to the $resource object in addition to the existing one (articleId), you may have to create another $resource service with the new parameter (:tag) and use it in your search method in your angular controller.
Another way that sounds more simple and flexible to me is to just pass the search parameters in the query method, like this:
$scope.searchart = function() {
Articles.query({tag:$scope.selectedTag}, function(articles) {
$scope.articles = articles;
});
};
and then at the server side controller, read your query parameters like this:
exports.searcharticle = function(req, res) {
Article.find(req.query).sort('-created').populate('user', 'name username').exec(function(err, articles) {
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(articles);
}
});
};

magicSuggest is not updating/refreshing data: on ajax success

Below is the code i'm using to populate data for magicSuggest box. For the first time it is getting correct values in dropdown but on change of dependent dropdown its not changing its data.
$(document).on("change",".specilitydrop", function() {
var select = $(this);
var newVal = select.val();
//alert(newVal);
$.ajax({
type: 'Post',
url : "<?php echo LIVE_SITE; ?>/users/findSubSplProfile/"+newVal,
success: function (data)
{ $('#subSpecialityData').magicSuggest({
width: 495,
sortOrder: 'value',
selectionPosition: 'bottom',
selectionStacked: true,
displayField: 'value',
data: $.parseJSON(data)
});
}
});
});
Thanks in advance
Calling $('#subSpecialityData').magicSuggest multiple times won't create multiple components. Rather it will keep the same component. If you want to set new data every time, you should delete the component and its associated DOM prior to recreating it.
You should pass data by using magicSuggest's option, instead of ajax callback
$('#subSpecialityData').magicSuggest({
width: 495,
sortOrder: 'value',
selectionPosition: 'bottom',
selectionStacked: true,
displayField: 'value',
method: "post",
data: "users/findSubSplProfile/"+newVal
});

Resources