YUI3 Tabview How to determine the label of selected tab - yui

I need a YUI3 tabview like
<div id="demo"></div>
<script>
YUI().use('tabview', function(Y) {
var tabview = new Y.TabView({
children: [{
label: 'foo',
content: '<p>foo content</p>'
}, {
label: 'bar',
content: '<p>bar content</p>'
}, {
label: 'baz',
content: '<p>baz content</p>'
}]
});
tabview.render('#demo');
});
</script>
Now need a event handler which will be of following specification
It will be fired when user will click on tab something like "selectedTabChanged"
Inside the handler will determine the label of the "SelectedTab"

Just add this below tabview.render('#demo');
tabview.on('selectionChange', function (e) {
alert('Changing tab from "' + e.prevVal.get('label') + '" to "' + e.newVal.get('label') + '"');
}

Related

cart product quantity is 1 when we decrement product will be remove how to set a sweetalert in removing product using ajax

cart product quantity is 1 when we decrement product will be remove how to set a sweetalert in removing product using ajax
how to worksweetalert in ajax
this is the html code:-
-
{{this.quantity}}
+
this is the script code
<script>
function changeQuantity(cartId,proId,userId,count){
let quantity=parseInt(document.getElementById(proId).innerHTML)
count=parseInt(count)
console.log(userId)
$.ajax({
url:'/change-product-quantity',
data:{
user:userId,
cart:cartId,
product:proId,
count:count,
quantity:quantity
},
method:'post',
success:(response)=>{
if(response.removeProduct){
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.isConfirmed) {
{
// window.location=value
location.reload()
}
}
})
/* alert('product reoved from cart')
location.reload() */
}else{
document.getElementById(proId).innerHTML=quantity+count
document.getElementById('total').innerHTML=response.total
}
}
})
}
</script>

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>

Angular 2: Load data using Server data source into my ng smart table

Has any one figure out on how to load the server data from the ng2-smart table plugin of Angular2.
I have few products data that is retrieved from Node API and Im able to display the same onClick event in the browser log.
I need to display the same in this 3rd party plugins table area which they have provided in this documentation below:
Frontend : https://akveo.github.io/ng2-smart-table/#/examples/populate-from-server
Under "Server Data Source Example"
Code: https://github.com/akveo/ng2-smart-table/blob/master/src/app/pages/examples/server/advanced-example-server.component.ts
Accordingly i have configured in my code as below:
blank-page.component.ts
import { ServerDataSource } from 'ng2-smart-table';
import { Component } from '#angular/core';
import { Http } from '#angular/http';
#Component({
selector: 'advanced-example-server',
template: `
<ng2-smart-table [settings]="settings" [source]="source"></ng2-smart-table>
`,
})
export class BlankPageComponent implements OnInit {
settings = {
columns: {
id: {
title: 'ID',
},
albumId: {
title: 'Album',
},
title: {
title: 'Title',
},
url: {
title: 'Url',
},
},
};
source: ServerDataSource;
//Doubt or Problem here!!!
constructor(http: Http) {
this.source = new ServerDataSource(http, { endPoint: 'https://jsonplaceholder.typicode.com/photos' });
}
//Tried like this too (Which is not the right way of calling)
constructor(http: Http) {
this.source = new ServerDataSource(http, { endPoint: this.productService.getProductsOncategory(this.categoryid) });
}
//Dint work this too!!
constructor(http: Http) {
this.source = new ServerDataSource(http, { endPoint:'http://localhost:5000/products/getProductsOncategory ' });
}
}
Where my service.ts file is like, which actually displays the products data in my browser log which i need to show in my table data
getProductsOncategory(category_id){
let catUrl="http://localhost:5000/products/getProductsOncategory"
let headers = new Headers();
headers.append('Content-Type','application/json');
let catIdObj = JSON.stringify({category_id:category_id})
console.log(catIdObj)
return this.http.post(catUrl,catIdObj,{headers:headers})
.map((response:Response)=>response.json())
.do(data=>console.log(JSON.stringify(data)))
.catch(this.handleError);
}
Error if i use my projects url in endpoint
Error: Uncaught (in promise): Error: Data must be an array. Please check that data extracted from the server response by the key '' exists and is array.
This is what i did and worked perfect for me, i used smart table server side paging, but build my own filter for custom filtration experience.
1- Define Server Data Source
source: ServerDataSource;
2- set it in constructor with config object
this.source = new ServerDataSource(http,
{
endPoint: 'full-url-for-endpoint',
dataKey: 'your-list-path-from-response' for example 'data.records' ,
pagerPageKey: 'your backend param excpected for page number key',
pagerLimitKey: 'your backend param excpected for page size',
totalKey: total records returned in response path for example 'data.total',
filterFieldKey: your filter keys template should set to '#field#' if you need to send params as you set, Default is '#field#_like'
});`
3- add settings object
settings = {
actions: {
custom: [ // if you need custom actions do like that
{ name: 'view-something', title: '<i title="Exception" class="nb-alert"></i>' },
{ name: 'do-custom', title: '<i class="fa fa-pencil"></i>' }
],
add: true, //if you don't need default add button set to false
edit: true, //if you don't need default add button set to false
delete: true, //if you don't need default delete button set to false
position: 'right' // buttons position
}, // remove add , edit , delete objects if you don't use
add: {
addButtonContent: '<i class="nb-plus"></i>',
createButtonContent: '<i class="nb-checkmark"></i>',
cancelButtonContent: '<i class="nb-close"></i>',
},
edit: {
editButtonContent: '<i class="nb-edit"></i>',
saveButtonContent: '<i class="nb-checkmark"></i>',
cancelButtonContent: '<i class="nb-close"></i>',
},
delete: {
deleteButtonContent: '<i class="nb-trash"></i>',
confirmDelete: true,
},
pager: {
display: true // set to false if no need for pagination
},
columns: {
Id: { // set up table cols - Id is a prop name returned from backend
title: 'ID', // display name in table header
type: 'number',
filter: false // add text filter for it or not
},
Name: {
title: 'Full Name',
type: 'string',
filter: false
}
}
};
// Add Filter Data , i used a custom form binded with ngModel above table for filtration, so assume you have a model called filter which get data from external form
FilterData() {
this.source.reset(true); // reset your old filtered data
this.source.setPage(1, false); // set page to 1 to start from beginning
let filterArr = this.getFilterArray(); // add a new filter data, but be careful to not sent any empty data, as it throws an exception
if (filterArr.length)
this.source.setFilter(filterArr, false, false);
this.source.refresh(); // this will call the server with new filter and paginatio data
}
getFilterArray() { // setup new filter
let filterArray = [];
if (this.filter.id)
filterArray.push({ field: 'id', search: this.filter.id });
if (this.filter.name)
filterArray.push({ field: 'name', search: this.filter.name});
return filterArray;
}
onCustomAction(event) { // custom buttons code
switch (event.action) {
case 'view-something':
// put your code here
break;
default:
console.log('Not Implemented Action');
break;
}
}
With this example my data is resource so the datakey is set resource
find below sample code
{
source: ServerDataSource;
constructor(http: HttpClient) {
this.source = new ServerDataSource(http, { dataKey: 'resource', endPoint:'http://localhost:8080/api/v2/mysql/_table/able' })
}
You need to set the dataKey for the ServerDataSource. For example, if your JSON is { data: [...], total: .. }, you need to set dataKey = 'data'.
this worked for me on Angular 8, But Search box functionality needs to be handeled from backend (i.e: localhost:5000/session_info/Seance1?temp_like=30), so backend need to filter (temp_like = value) in database, which make search box retrive live data.
Here is the entire component with Edit and Delete, Enjoy it!
import {Component} from '#angular/core';
import {ServerDataSource} from 'ng2-smart-table';
import {HttpClient} from "#angular/common/http";
import {Setting} from "../../setting";
#Component({
selector: 'ngx-session-man',
templateUrl: './sessions-man.component.html',
styleUrls: ['./sessions-man.component.scss'],
})
export class SessionsManComponent {
settings = {
mode: 'inline',
add: {
addButtonContent: '<i class="nb-plus"></i>',
createButtonContent: '<i class="nb-checkmark"></i>',
cancelButtonContent: '<i class="nb-close"></i>',
},
edit: {
editButtonContent: '<i class="nb-edit"></i>',
saveButtonContent: '<i class="nb-checkmark"></i>',
cancelButtonContent: '<i class="nb-close"></i>',
confirmSave: true,
},
delete: {
deleteButtonContent: '<i class="nb-trash"></i>',
confirmDelete: true,
},
columns: {
name: {
title: 'Séance',
type: 'string',
},
start: {
title: 'Début',
type: 'any',
},
end: {
title: 'Fin',
type: 'any',
},
},
};
source: ServerDataSource;
constructor(private httpClient: HttpClient) {
this.source = new ServerDataSource(this.httpClient, {endPoint: Setting.baseUrl + 'all_sessions_table'});
}
onDeleteConfirm(event): void {
if (window.confirm('Are you sure you want to delete ' + event['data']['name'] + '?')) {
event.confirm.resolve();
this.httpClient.delete<any>('http://localhost:5000/del-seance/' + event['data']['name']).subscribe(
temps => {});
} else {
event.confirm.reject();
}
}
onEditConfirm(event): void {
if (window.confirm('Are you sure you want to edit ' + event['data']['name'] + '\'s name to ' + event['newData']['name'] + '?')) {
event.confirm.resolve();
this.httpClient.post<any>('http://localhost:5000/mod-seance/' + event['data']['name'] + '/' + event['newData']['name'], { title: 'Session deleted' }).subscribe(
temps => {});
} else {
event.confirm.reject();
}
}
}

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

Collection and view not working in backbone script?

Hey guys I am currently following a tutorial and learning backbone, but for some reason I cannot get anything besides the Backbone model to work. Everything underneath it such as the collection or view does not seem to respond when entering things in the console. This is currently my code, I cannot find anything wrong with it and it validates in JSLint. One thing I noticed though is that the video is from before the 1.0 update of backbone. I am using jade for the layout and will include the code below as well.
UPDATED: I am working with this now.
(function(){
//app can be the name of the project/app
window.App = {
Models: {},
Collections: {},
Views: {},
Templates: {},
Routes: {}
};
window.template = function (id) {
return _.template($('#' + id).html());
};
//Can get rid of the Collection and views out of the names of each
//User Model
App.Models.User = Backbone.Model.extend({
defaults: {
firstName: 'J.R.',
lastName: 'Smith',
email: 'jsmith#knicks.com',
phone: '212-424-6234',
birthday: '03/05/1982',
city: 'New York'
},
location: function(){
return this.get('firstName') + ' ' + this.get('lastName') + 'is currently in ' + this.get('city') + '.';
}
});
// list of users
App.Collections.UsersCollection = Backbone.Collection.extend({
model: App.Models.User
});
//User View
App.Views.UserView = Backbone.View.extend({
tagName: 'li',
events: {
'click .edit':
},
template: template('userTemplate'),
initialize: function() {
this.render();
},
render: function() {
var template = this.template(this.model.toJSON());
this.$el.html(template);
return this;
//always return this on render methods
}
});
// view for users
App.Views.UsersView = Backbone.View.extend({
tagName: 'ul',
initialize: function() {
},
render: function() {
this.collection.each(function(user) {
//user is the model associated to the new created user
var userView = new App.Views.UserView({model: user});
this.$el.append(userView.el);
}, this);
}
});
var userView = new App.Views.UserView({model: User});
$(document.body).append(userView.render().el);
})();
Jade layout page
doctype 5
html
head
title=title
link(rel='stylesheet', href='/css/style.css', type='text/css')
link(rel='stylesheet', href='/css/bootstrap-responsive.css')
link(href='/css/bootstrap.css', rel='stylesheet', type='text/css')
link(href='/css/font-awesome.min.css', rel='stylesheet', type='text/css')
script(src='/js/jquery.min.js', type='text/javascript')
script(src='/js/jquery.validate.min.js', type='text/javascript')
script(src='/js/script.js', type='text/javascript')
script(src='/js/underscore.min.js', type='text/javascript')
script(src='/js/backbone.min.js', type='text/javascript')
body
div#container
div#header
block content
include footer
Jade index page
extends layout
block content
h1= title
p Welcome to #{title}
script(src='/js/main.js', type='text/javascript')
script(id='userTemplate', type='text/template')
<%=firstName%>
button.edit Edit
<%=lastName%>
button.edit Edit
<%=email%>
button.edit Edit
<%=phone%>
button.edit Edit
<%=birthday%>
button.edit Edit
<%=city%>
button.edit Edit
A view's render method simply fills in the view's el, someone else has to add that el to the page that people will see. You're using tagName in your view:
tagName: 'li'
That just means that Backbone will create an <li> as your view's el, it doesn't mean that that <li> will be added to anything. The usual pattern is for render to return this:
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
and then whoever is calling render can add the el to the page with something like this:
var userView = new UserView({model: user});
$(whatever).append(userView.render().el);
I do my Backbone work client-side so I'm not sure how that would fit into your set up.
I think the problem lies here:
var userView = new App.Views.UserView({model: User});
$(document.body).append(userView.render().el);
Looking at your code I would expect an instance of App.Views.UsersView to be appended, and for it to be populated - in the code above you're pushing in { model: User } to an instance of a UserView instance rather than an instance of UsersCollection to an instance of UsersView.
Firstly your UsersView.render method should return this; in order to allow use of the .render().el pattern, UsersView handles creating and attaching instances of UserView for each model in the collection so you don't need to worry about this again.
render: function() {
this.collection.each(function(user) {
//user is the model associated to the new created user
var userView = new App.Views.UserView({model: user});
this.$el.append(userView.el);
}, this);
return this;
}
Then, the following looks right to me:
var users_data=[{
firstName: 'A',
lastName: 'Person',
email: 'a#knicks.com',
phone: '212-424-6234',
birthday: '03/05/1982',
city: 'New York'
},
firstName: 'Another',
lastName: 'Person',
email: 'another#knicks.com',
phone: '212-424-6234',
birthday: '03/05/1982',
city: 'New York'
},
firstName: 'A',
lastName: 'Person',
email: 'a#knicks.com',
phone: '212-424-6234',
birthday: '03/05/1982',
city: 'New York'
}];
var users = new App.Collections.UsersCollection( users_data );
var usersView = new App.Views.UsersView( users );
$( document.body ).append( usersView.render().el );

Resources