Update vuejs model value using jquery-chosen plugin - jquery-chosen

Trying to use jquery-chosen with vue, the problem is that this plugin hides the actual select that I applied v-model, so when I select a value vue doesn't recognize it as a select change event and model value is not updated.
The value of the select is being changed actually when I select something, I've inspected this with console.log to see the selected value.
http://jsfiddle.net/qfy6s9Lj/3/
I could do vm.$data.city = $('.cs-select').val(), that seems to work,
But is there another option? If the value of the select was changed why vue doesn't see this?

#swift's answer got pretty close, but as #bertrand pointed out, it doesn't work for multiselects. I've worked something out that works with both cases: http://jsfiddle.net/seanwash/sz8s99xx/
I would have just commented but I don't have enough rep to do so.
Vue.directive('chosen', {
twoWay: true, // note the two-way binding
bind: function () {
$(this.el)
.chosen({
inherit_select_classes: true,
width: '30%',
disable_search_threshold: 999
})
.change(function(ev) {
// two-way set
// Construct array of selected options
var i, len, option, ref;
var values = [];
ref = this.el.selectedOptions;
for (i = 0, len = ref.length; i < len; i++) {
option = ref[i];
values.push(option.value)
}
this.set(values);
}.bind(this));
},
update: function(nv, ov) {
// note that we have to notify chosen about update
$(this.el).trigger("chosen:updated");
}
});
var vm = new Vue({
data: {
city: 'Toronto',
cities: [{text: 'Toronto', value: 'Toronto'},
{text: 'Orleans', value: 'Orleans'}]
}
}).$mount("#search-results");

I am opened for other suggestions, but for the time-being I did it this way:
html
<div id='search-results'>
{{city}}
<select class="cs-select" v-model='city'>
<option value="Toronto">Toronto</option>
<option value="Orleans">Orleans</option>
</select>
</div>
js
window.vm = new Vue({
el: '#search-results',
data: {
city: 'Toronto',
}
})
$('.cs-select').chosen({
inherit_select_classes: true,
width: '30%'
}).change( function() {
vm.$data.city = $('.cs-select').val()
})

Update: Be advised this doesn't work from within a v-for loop. A related question that deals with that is available here.
Going off of #kaktuspalme's solution, and with help from my friend Joe Fleming, I came up with a solution that works with Vue 2 and allows single and multiple selections:
Vue.directive('chosen', {
inserted: function(el, binding, vnode) {
jQuery(el).chosen().change(function(event, change) {
if (Array.isArray(binding.value)) {
var selected = binding.value;
if (change.hasOwnProperty('selected')) {
selected.push(change.selected);
} else {
selected.splice(selected.indexOf(change.deselected), 1);
}
} else {
var keys = binding.expression.split('.');
var pointer = vnode.context;
while (keys.length > 1)
pointer = pointer[keys.shift()];
pointer[keys[0]] = change.selected;
}
});
},
componentUpdated: function(el, binding) {
jQuery(el).trigger("chosen:updated");
}
});
Use it like this:
<select v-model="mymodel" v-chosen="mymodel">...</select>
It works with multiple="multiple" and even with nested state, e.g.:
<select v-model="nested.mymodel" v-chosen="nested.mymodel">...</select>
See the fiddle here: https://jsfiddle.net/tylercollier/bvvvgyp0/5/

Answer:
http://jsfiddle.net/qfy6s9Lj/5/
<div id='search-results'>
Vue model value <br>
{{city}}
<hr>
Select value:
<select class="cs-select" v-chosen>
<option value="Toronto">Toronto</option>
<option value="Orleans">Orleans</option>
</select>
</div>
Vue.directive('chosen', {
bind: function () {
var vm = this.vm;
this.el.options = vm.cities;
this.el.value = vm.city;
$(this.el).chosen({
inherit_select_classes: true,
width: '30%',
disable_search_threshold: 999})
.change( function() {
vm.city = this.el.value;
}.bind(this)
);
}
});
var vm = new Vue({
data: {
city: 'Toronto',
cities: ['Toronto', 'Orleans']
}
}).$mount("#search-results");
UPDATE: an even better solution (thanks to simplesmiler):
http://jsfiddle.net/simplesmiler/qfy6s9Lj/8/

I made an update for vue2.
Vue.directive('chosen', {
selected: null,
inserted: function (el, binding) {
selected = binding.value;
$(el).chosen().change(function(event, change) {
if(change.hasOwnProperty('selected')) {
selected.push(change.selected);
} else {
selected.splice(selected.indexOf(change.deselected), 1);
}
});
},
componentUpdated: function(el, binding) {
selected = binding.value;
$(el).trigger("chosen:updated");
}
});
var vm = new Vue({
el: '#app',
data: {
selected: [],
cities: [{id: 1, value: "Toronto"}, {id: 2, value: "Orleans"}, {id: 3, value: "Bern"}]
}
});
See: https://jsfiddle.net/kaktuspalme/zenksm2b/

Code taken from #kaktuspalme answer. It works with non-multiple elements now and only for non-multiple.
Vue.directive('chosensingle', {
inserted: function (el, binding) {
var selected = binding.value;
$(el).chosen().change(function(event, change) {
if(change.hasOwnProperty('selected')) {
selected.value = change.selected;
} else {
selected.value ='';
}
});
},
componentUpdated: function(el, binding) {
$(el).trigger("chosen:updated");
}
});
Comments from #Tyler Collier are taken into account
But be carefully,property you use in v-model should be defined as array , e.g. applicantId: [] otherwise it doesn't work

Related

How to use formatter method with async call

im try to display some data using b-table and the formatter method using axios with the spread method but this its not displaying correctly.
this is what i have https://codepen.io/damian-garrido/pen/MWgxqeZ
html template
<div id="app">
<b-table
:fields="fields"
:items="items">
</b-table>
</div>
js file
window.onload = () => {
new Vue({
el: '#app',
data() {
return {
fields: [
{
key: 'owner',
label: 'Poke Owner'
},
{
key: 'pokemonIds',
label: 'Poke Name',
formatter: 'getPokeName'
}
],
items: [
{
owner: 'Juan',
pokemonIds: [3,4]
},
{
owner: 'Diego',
pokemonIds: [7,9,14]
}
]
}
},
methods: {
getPokeName: function (pokeIds) {
let promises = []
for (let id of pokeIds) {
promises.push(axios.get(`https://pokeapi.co/api/v2/pokemon/${id}`))
}
axios.all(promises)
.then( axios.spread((...responses) => {
let names = ''
for (let r of responses) {
names += r.data.name + ', '
}
console.log(names)
return names
}))
}
}
})
}
the console.log return the names, as i need, but not display this on the table.
Table formatter methods must be synchronous.
You would need to make your formatter an async method that uses await to return the value from your formatter. Note that this will slow your app rendering to a crawl as each row will have to wait for the async call to finish before it can render the table row.
Your best bet would be to do the lookup processing in your app, and then pass that data to the table.

Setting state in react. Is there a better way to write this without warning errors?

I am working on a registration form on react. I am a bit stuck with the validation part of it.
As of now I am getting the following warnings four times on the console: "warning Do not mutate state directly. Use setState() react/no-direct-mutation-state."
I am guessing the reason I am getting these errors is because of statements like these "this.state.errors.firstName = "First name must be at least 2 characters.";" and like this"this.state.errors = {};" in my code.
However, I do not know how to make this better and eliminate the warnings. If you can provide a better way for me to do this that would be awesome. Any help will be highly appreciated. Thanks so much in advance!
import React, { Component } from 'react';
import {withRouter} from "react-router-dom";
import HeaderPage from './HeaderPage';
import Logo from './Logo';
import RegistrationForm from './RegistrationForm';
import axios from 'axios';
class Registration extends Component {
mixins: [
Router.Navigation
];
constructor(props) {
super(props);
this.state = {
firstName:'',
lastName:'',
email:'',
errors:{},
helpText: '',
helpUrl: '',
nextLink:''
};
this.setUserState = this.setUserState.bind(this);
this.registrationFormIsValid = this.registrationFormIsValid.bind(this);
this.saveUser = this.saveUser.bind(this);
}
setUserState(e){
const target = e.target;
const value = target.value;
const name = target.name;
this.setState({[name]: value});
//delete this line
console.log(this.state[name]);
}
registrationFormIsValid(){
var formIsValid = true;
this.state.errors = {};
//validate first name
if(this.state.firstName.length < 2){
this.state.errors.firstName = "First name must be at least 2 characters.";
formIsValid = false;
}
//validate last name
if(this.state.lastName.length < 2){
this.state.errors.lastName = "Last name must be at least 2 characters.";
formIsValid = false;
}
//validate email
if(this.state.email.length < 2){
this.state.errors.email = "Email must be at least 2 characters.";
formIsValid = false;
}
this.setState({errors : this.state.errors});
return formIsValid;
}
saveUser(e, { history }){
e.preventDefault();
// const errorWrappers = document.getElementsByClassName('input');
// for (var i=0; i < errorWrappers.length; i++) {
// const isError= errorWrappers[i].innerHTML;
// if (isError.length > 0){
// errorWrappers[i].previousSibling.className = "error-input"
// }
// }
if(!this.registrationFormIsValid()){
return;
}
const values = {
firstName: this.state.firstName,
lastName: this.state.lastName,
email: this.state.email,
password: this.state.password,
phone: this.state.phone,
address: this.state.address,
dob: this.state.birthday
}
if (this.props.userRole === 'instructor'){
axios.post(`/instructors`, values)
.then((response)=> {
//delete this line
console.log(response);
})
.catch((error) => {
console.log(error + 'something went wrooooong');
});
this.props.history.push("/success-instructor");
}else{
axios.post(`/students`, values)
.then((response)=> {
//delete this line
console.log(response);
})
.catch((error) => {
console.log(error + 'something went wrooooong');
});
if (this.props.parent === "false"){
this.props.history.push("/success-student");
}else{
this.props.history.push("/success-parent");
}
}
}
//end of validation
render() {
return (
<div className="Registration">
<div className="container menu buttons">
<HeaderPage/>
</div>
<div className="page container narrow">
<div className="cover-content">
<Logo/>
<div className="container">
<h2 className="page-title">{this.props.title}</h2>
<a className="helpLink" href={this.props.helpUrl}>{this.props.helpText}</a>
<div className="main-content background-white">
<RegistrationForm
userRole={this.props.userRole}
onChange={this.setUserState}
onSave={this.saveUser}
errors={this.state.errors}
/>
<br/>
<br/>
<br/>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default withRouter(Registration);
Instead of
this.state.errors = {};
and
this.state.errors.lastName = "Last name must be at least 2 characters.";
use
this.setState({errors = {}});
this.setState({ errors: { lastName: "Last name must be at least 2 characters." } });
You need to avoid directly mutating the state.
The Warning itself answers the question. Please read the React Doc
carefully.
"warning Do not mutate state directly. Use setState()
react/no-direct-mutation-state."
Do not mutate state
Don't ever have code that directly changes state. Instead, create new object and change it. After you are done with changes update state with setState.
Instead of:
this.state.errors.someError1="e1";
this.state.errors.someError2="e2";
do this:
this.errorsObject=Object.assign({},this.state.errors,{someError1:"e1",someError2:"e2"};
and in the end:
this.setState({
errors:this.errorsObject
});
Object.assign lets us merge one object's properties into another one, replacing values of properties with matching names. We can use this to copy an object's values without altering the existing one.

How to use a checkbox for a boolean data with ag-grid

I have searched for awhile now and haven't seen any real example of this.
I am using ag-grid-react and I would like for a column that holds a boolean to represent that boolean with a checkbox and update the object in the rowData when changed.
I know there is checkboxSelection and I tried using it like what I have below, but realized while it's a checkbox, it's not linked to the data and is merely for selecting a cell.
var columnDefs = [
{ headerName: 'Refunded', field: 'refunded', checkboxSelection: true,}
]
So is there a way to do what I am looking for with ag-grid and ag-grid-react?
You should use the cellRenderer property
const columnDefs = [{ headerName: 'Refunded',
field: 'refunded',
editable:true,
cellRenderer: params => {
return `<input type='checkbox' ${params.value ? 'checked' : ''} />`;
}
}];
I was stuck in the same problem , this is the best I could come up with but I wasn't able to bind the value to this checkbox.
I set the cell property editable to true , now if you want to change the actual value you have to double click the cell and type true or false.
but this is as far as I went and I decided to help you , I know it doesn't 100% solve it all but at least it solved the data presentation part.
incase you found out how please share your answers with us.
What about this? It's on Angular and not on React, but you could get the point:
{
headerName: 'Enabled',
field: 'enabled',
cellRendererFramework: CheckboxCellComponent
},
And here is the checkboxCellComponent:
#Component({
selector: 'checkbox-cell',
template: `<input type="checkbox" [checked]="params.value" (change)="onChange($event)">`,
styleUrls: ['./checkbox-cell.component.css']
})
export class CheckboxCellComponent implements AfterViewInit, ICellRendererAngularComp {
#ViewChild('.checkbox') checkbox: ElementRef;
public params: ICellRendererParams;
constructor() { }
agInit(params: ICellRendererParams): void {
this.params = params;
}
public onChange(event) {
this.params.data[this.params.colDef.field] = event.currentTarget.checked;
}
}
Let me know
We can use cellRenderer to show checkbox in grid, which will work when you want to edit the field also. Grid will not update the checkbox box value in the gridoption - rowdata directly till you do not update node with respective field in node object which can be access by params object.
params.node.data.fieldName = params.value;
here fieldName is field of the row.
{
headerName: "display name",
field: "fieldName",
cellRenderer: function(params) {
var input = document.createElement('input');
input.type="checkbox";
input.checked=params.value;
input.addEventListener('click', function (event) {
params.value=!params.value;
params.node.data.fieldName = params.value;
});
return input;
}
}
Here's how to create an agGrid cell renderer in Angular to bind one of your columns to a checkbox.
This answer is heavily based on the excellent answer from user2010955's answer above, but with a bit more explanation, and brought up-to-date with the latest versions of agGrid & Angular (I was receiving an error using his code, before adding the following changes).
And yes, I know this question was about the React version of agGrid, but I'm sure I won't be the only Angular developer who stumbles on this StackOverflow webpage out of desperation, trying to find an Angular solution to this problem.
(Btw, I can't believe it's 2020, and agGrid for Angular doesn't come with a checkbox renderer included by default. Seriously ?!!)
First, you need to define a renderer component:
import { Component } from '#angular/core';
import { ICellRendererAngularComp } from 'ag-grid-angular';
import { ICellRendererParams } from 'ag-grid-community';
#Component({
selector: 'checkbox-cell',
template: `<input type="checkbox" [checked]="params.value" (change)="onChange($event)">`
})
export class CheckboxCellRenderer implements ICellRendererAngularComp {
public params: ICellRendererParams;
constructor() { }
agInit(params: ICellRendererParams): void {
this.params = params;
}
public onChange(event) {
this.params.data[this.params.colDef.field] = event.currentTarget.checked;
}
refresh(params: ICellRendererParams): boolean {
return true;
}
}
Next, you need to tell your #NgModule about it:
import { CheckboxCellRenderer } from './cellRenderers/CheckboxCellRenderer';
. . .
#NgModule({
declarations: [
AppComponent,
CheckboxCellRenderer
],
imports: [
BrowserModule,
AgGridModule.withComponents([CheckboxCellRenderer])
],
providers: [],
bootstrap: [AppComponent]
})
In your Component which is displaying the agGrid, you need to import your renderer:
import { CheckboxCellRenderer } from './cellRenderers/CheckboxCellRenderer';
Let's define a new columns for our grid, some of which will use this new renderer:
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
#ViewChild('exampleGrid', {static: false}) agGrid: AgGridAngular;
columnDefs = [
{ headerName: 'Last name', field: 'lastName', editable: true },
{ headerName: 'First name', field: 'firstName', editable: true },
{ headerName: 'Subscribed', field: 'subscribed', cellRenderer: 'checkboxCellRenderer' },
{ headerName: 'Is overweight', field: 'overweight', cellRenderer: 'checkboxCellRenderer' }
];
frameworkComponents = {
checkboxCellRenderer: CheckboxCellRenderer
}
}
And now, when you're creating your agGrid, you need to tell it about the home-made framework components which you're using:
<ag-grid-angular #exampleGrid
style="height: 400px;"
class="ag-theme-material"
[rowData]="rowData"
[columnDefs]="columnDefs"
[frameworkComponents]="frameworkComponents" >
</ag-grid-angular>
Phew!
Yeah... it took me a while to work out how to make all the pieces fit together. agGrid's own website really should've included an example like this...
The code below helps address the issue. The downside is that the normal events in gridOptions will not fired (onCellEditingStarted, onCellEditingStopped,onCellValueChanged etc).
var columnDefs = [...
{headerName: "Label", field: "field",editable: true,
cellRenderer: 'booleanCellRenderer',
cellEditor:'booleanEditor'
}
];
//register the components
$scope.gridOptions = {...
components:{
booleanCellRenderer:BooleanCellRenderer,
booleanEditor:BooleanEditor
}
};
function BooleanCellRenderer() {
}
BooleanCellRenderer.prototype.init = function (params) {
this.eGui = document.createElement('span');
if (params.value !== "" || params.value !== undefined || params.value !== null) {
var checkedStatus = params.value ? "checked":"";
var input = document.createElement('input');
input.type="checkbox";
input.checked=params.value;
input.addEventListener('click', function (event) {
params.value=!params.value;
//checked input value has changed, perform your update here
console.log("addEventListener params.value: "+ params.value);
});
this.eGui.innerHTML = '';
this.eGui.appendChild( input );
}
};
BooleanCellRenderer.prototype.getGui = function () {
return this.eGui;
};
function BooleanEditor() {
}
BooleanEditor.prototype.init = function (params) {
this.container = document.createElement('div');
this.value=params.value;
params.stopEditing();
};
BooleanEditor.prototype.getGui = function () {
return this.container;
};
BooleanEditor.prototype.afterGuiAttached = function () {
};
BooleanEditor.prototype.getValue = function () {
return this.value;
};
BooleanEditor.prototype.destroy = function () {
};
BooleanEditor.prototype.isPopup = function () {
return true;
};
React specific solution
When using React (16.x) functional component with React Hooks make it easy to write your cellRenderer. Here is the function equivalent of what pnunezcalzado had posted earlier.
React component for the cell Renderer
function AgGridCheckbox (props) {
const boolValue = props.value && props.value.toString() === 'true';
const [isChecked, setIsChecked] = useState(boolValue);
const onChanged = () => {
props.setValue(!isChecked);
setIsChecked(!isChecked);
};
return (
<div>
<input type="checkbox" checked={isChecked} onChange={onChanged} />
</div>
);
}
Using it in your grid
Adjust your column def (ColDef) to use this cell renderer.
{
headerName: 'My Boolean Field',
field: 'BOOLFIELD',
cellRendererFramework: AgGridCheckbox,
editable: true,
},
Frameworks - React/Angular/Vue.js
You can easily integrate cell renderers with any JavaScript framework you're using to render ag-Grid, by creating your cell renderers as native framework components.
See this implemented in React in the code segment below:
export default class extends Component {
constructor(props) {
super(props);
this.checkedHandler = this.checkedHandler.bind(this);
}
checkedHandler() {
let checked = event.target.checked;
let colId = this.props.column.colId;
this.props.node.setDataValue(colId, checked);
}
render() {
return (
<input
type="checkbox"
onClick={this.checkedHandler}
checked={this.props.value}
/>
)
}
}
Note: There are no required lifecycle methods when creating cell renderers as framework components.
After creating the renderer, we register it to ag-Grid in gridOptions.frameworkComponents and define it on the desired columns:
// ./index.jsx
this.frameworkComponents = {
checkboxRenderer: CheckboxCellRenderer,
};
this.state = {
columnDefs: [
// ...
{
headerName: 'Registered - Checkbox',
field: 'registered',
cellRenderer: 'checkboxRenderer',
},
// ...
]
// ....
Please see below live samples implemented in the most popular JavaScript frameworks (React, Angular, Vue.js):
React demo.
Angular demo.
Note: When using Angular it is also necessary to pass custom renderers to the #NgModule decorator to allow for dependency injection.
Vue.js demo.
Vanilla JavaScript
You can also implement the checkbox renderer using JavaScript.
In this case, the checkbox renderer is constructed using a JavaScript Class. An input element is created in the ag-Grid init lifecycle method (required) and it's checked attribute is set to the underlying boolean value of the cell it will be rendered in. A click event listener is added to the checkbox which updates this underlying cell value whenever the input is checked/unchecked.
The created DOM element is returned in the getGui (required) lifecycle hook. We have also done some cleanup in the destroy optional lifecycle hook, where we remove the click listener.
function CheckboxRenderer() {}
CheckboxRenderer.prototype.init = function(params) {
this.params = params;
this.eGui = document.createElement('input');
this.eGui.type = 'checkbox';
this.eGui.checked = params.value;
this.checkedHandler = this.checkedHandler.bind(this);
this.eGui.addEventListener('click', this.checkedHandler);
}
CheckboxRenderer.prototype.checkedHandler = function(e) {
let checked = e.target.checked;
let colId = this.params.column.colId;
this.params.node.setDataValue(colId, checked);
}
CheckboxRenderer.prototype.getGui = function(params) {
return this.eGui;
}
CheckboxRenderer.prototype.destroy = function(params) {
this.eGui.removeEventListener('click', this.checkedHandler);
}
After creating our renderer we simply register it to ag-Grid in our gridOptions.components object:
gridOptions.components = {
checkboxRenderer: CheckboxRenderer
}
And define the renderer on the desired column:
gridOptions.columnDefs = [
// ...
{
headerName: 'Registered - Checkbox',
field: 'registered',
cellRenderer: 'checkboxRenderer',
},
// ...
Please see this implemented in the demo below:
Vanilla JavaScript.
Read the full blog post on our website or check out our documentation for a great variety of scenarios you can implement with ag-Grid.
Ahmed Gadir | Developer # ag-Grid
Here is a react hooks version, set columnDef.cellEditorFramework to this component.
import React, {useEffect, forwardRef, useImperativeHandle, useRef, useState} from "react";
export default forwardRef((props, ref) => {
const [value, setValue] = useState();
if (value !== ! props.value) {
setValue(!props.value);
}
const inputRef = useRef();
useImperativeHandle(ref, () => {
return {
getValue: () => {
return value;
}
};
});
const onChange= e => {
setValue(!value);
}
return (<div style={{paddingLeft: "15px"}}><input type="checkbox" ref={inputRef} defaultChecked={value} onChange={onChange} /></div>);
})
I also have the following cell renderer which is nice
cellRenderer: params => {
return `<i class="fa fa-${params.value?"check-":""}square-o" aria-hidden="true"></i>`;
},
In the columnDefs, add a checkbox column. Don't need set the cell property editable to true
columnDefs: [
{ headerName: '', field: 'checkbox', cellRendererFramework: CheckboxRenderer, width:30},
...]
The CheckboxRenderer
export class CheckboxRenderer extends React.Component{
constructor(props) {
super(props);
this.state={
value:props.value
};
this.handleCheckboxChange=this.handleCheckboxChange.bind(this);
}
handleCheckboxChange(event) {
this.props.data.checkbox=!this.props.data.checkbox;
this.setState({value: this.props.data.checkbox});
}
render() {
return (
<Checkbox
checked={this.state.value}
onChange={this.handleCheckboxChange}></Checkbox>);
}
}
The array of the string values doesn't work for me, but array of [true,false] is working.
{
headerName: 'Refunded',
field: 'refunded',
cellEditor: 'popupSelect',
cellEditorParams: {
cellRenderer: RefundedCellRenderer,
values: [true, false]
}
},
function RefundedCellRenderer(params) {
return params.value;
}
You can use boolean (true or false)
I try this and it's work :
var columnDefs = [
{
headerName: 'Refunded',
field: 'refunded',
editable: true,
cellEditor: 'booleanEditor',
cellRenderer: booleanCellRenderer
},
];
Function checkbox editor
function getBooleanEditor() {
// function to act as a class
function BooleanEditor() {}
// gets called once before the renderer is used
BooleanEditor.prototype.init = function(params) {
// create the cell
var value = params.value;
this.eInput = document.createElement('input');
this.eInput.type = 'checkbox';
this.eInput.checked = value;
this.eInput.value = value;
};
// gets called once when grid ready to insert the element
BooleanEditor.prototype.getGui = function() {
return this.eInput;
};
// focus and select can be done after the gui is attached
BooleanEditor.prototype.afterGuiAttached = function() {
this.eInput.focus();
this.eInput.select();
};
// returns the new value after editing
BooleanEditor.prototype.getValue = function() {
return this.eInput.checked;
};
// any cleanup we need to be done here
BooleanEditor.prototype.destroy = function() {
// but this example is simple, no cleanup, we could
// even leave this method out as it's optional
};
// if true, then this editor will appear in a popup
BooleanEditor.prototype.isPopup = function() {
// and we could leave this method out also, false is the default
return false;
};
return BooleanEditor;
}
And then booleanCellRenderer function
function booleanCellRenderer(params) {
var value = params.value ? 'checked' : 'unchecked';
return '<input disabled type="checkbox" '+ value +'/>';
}
Let the grid know which columns and what data to use
var gridOptions = {
columnDefs: columnDefs,
pagination: true,
defaultColDef: {
filter: true,
resizable: true,
},
onGridReady: function(params) {
params.api.sizeColumnsToFit();
},
onCellValueChanged: function(event) {
if (event.newValue != event.oldValue) {
// do stuff
// such hit your API update
event.data.refunded = event.newValue; // Update value of field refunded
}
},
components:{
booleanCellRenderer: booleanCellRenderer,
booleanEditor: getBooleanEditor()
}
};
Setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
var gridDiv = document.querySelector('#myGrid');
// create the grid passing in the div to use together with the columns & data we want to use
new agGrid.Grid(gridDiv, gridOptions);
fetch('$urlGetData').then(function(response) {
return response.json();
}).then(function(data) {
gridOptions.api.setRowData(data);
})
});
Even though it's an old question, I developed a solution that may be interesting.
You can create a cell renderer component for the checkbox then apply it to the columns that must render a checkbox based on a boolean value.
Check the example below:
/*
CheckboxCellRenderer.js
Author: Bruno Carvalho da Costa (brunoccst)
*/
/*
* Function to work as a constructor.
*/
function CheckboxCellRenderer() {}
/**
* Initializes the cell renderer.
* #param {any} params Parameters from AG Grid.
*/
CheckboxCellRenderer.prototype.init = function(params) {
// Create the cell.
this.eGui = document.createElement('span');
this.eGui.classList.add("ag-icon");
var node = params.node;
var colId = params.column.colId;
// Set the "editable" property to false so it won't open the default cell editor from AG Grid.
if (params.colDef.editableAux == undefined)
params.colDef.editableAux = params.colDef.editable;
params.colDef.editable = false;
// Configure it accordingly if it is editable.
if (params.colDef.editableAux) {
// Set the type of cursor.
this.eGui.style["cursor"] = "pointer";
// Add the event listener to the checkbox.
function toggle() {
var currentValue = node.data[colId];
node.setDataValue(colId, !currentValue);
// TODO: Delete this log.
console.log(node.data);
}
this.eGui.addEventListener("click", toggle);
}
// Set if the checkbox is checked.
this.refresh(params);
};
/**
* Returns the GUI.
*/
CheckboxCellRenderer.prototype.getGui = function() {
return this.eGui;
};
/**
* Refreshes the element according to the current data.
* #param {any} params Parameters from AG Grid.
*/
CheckboxCellRenderer.prototype.refresh = function(params) {
var checkedClass = "ag-icon-checkbox-checked";
var uncheckedClass = "ag-icon-checkbox-unchecked";
// Add or remove the classes according to the value.
if (params.value) {
this.eGui.classList.remove(uncheckedClass);
this.eGui.classList.add(checkedClass);
} else {
this.eGui.classList.remove(checkedClass);
this.eGui.classList.add(uncheckedClass);
}
// Return true to tell the grid we refreshed successfully
return true;
}
/*
The code below does not belong to the CheckboxCellRenderer.js anymore.
It is the main JS that creates the AG Grid instance and structure.
*/
// specify the columns
var columnDefs = [{
headerName: "Make",
field: "make"
}, {
headerName: "Model",
field: "model"
}, {
headerName: "Price",
field: "price"
}, {
headerName: "In wishlist (editable)",
field: "InWishlist",
cellRenderer: CheckboxCellRenderer
}, {
headerName: "In wishlist (not editable)",
field: "InWishlist",
cellRenderer: CheckboxCellRenderer,
editable: false
}];
// specify the data
var rowData = [{
make: "Toyota",
model: "Celica",
price: 35000,
InWishlist: true
}, {
make: "Toyota 2",
model: "Celica 2",
price: 36000,
InWishlist: false
}];
// let the grid know which columns and what data to use
var gridOptions = {
columnDefs: columnDefs,
defaultColDef: {
editable: true
},
rowData: rowData,
onGridReady: function() {
gridOptions.api.sizeColumnsToFit();
}
};
// wait for the document to be loaded, otherwise
// ag-Grid will not find the div in the document.
document.addEventListener("DOMContentLoaded", function() {
// lookup the container we want the Grid to use
var eGridDiv = document.querySelector('#myGrid');
// create the grid passing in the div to use together with the columns & data we want to use
new agGrid.Grid(eGridDiv, gridOptions);
});
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/ag-grid/dist/ag-grid.js"></script>
</head>
<body>
<div id="myGrid" style="height: 115px;" class="ag-fresh"></div>
</body>
</html>
Please note that I needed to disable the editable property before ending the init function or else AG Grid would render the default cell editor for the field, having a weird behavior.
import React, { Component } from 'react';
export class CheckboxRenderer extends Component {
constructor(props) {
super(props);
if (this.props.colDef.field === 'noRestrictions') {
this.state = {
value: true,
disable: false
};
}
else if (this.props.colDef.field === 'doNotBuy') {
this.state = {
value: false,
disable: true
};
}
this.handleCheckboxChange = this.handleCheckboxChange.bind(this);
}
handleCheckboxChange(event) {
//this.props.data.checkbox=!this.props.data.checkbox; ={this.state.show}
//this.setState({value: this.props.data.checkbox});
if (this.state.value) { this.setState({ value: false }); }
else { this.setState({ value: true }); }
alert(this.state.value);
//check for the last row and check for the columnname and enable the other columns
}
render() {
return (
<input type= 'checkbox' checked = { this.state.value } disabled = { this.state.disable } onChange = { this.handleCheckboxChange } />
);
}
}
export default CheckboxRenderer;
import React, { Component } from 'react';
import './App.css';
import { AgGridReact } from 'ag-grid-react';
import CheckboxRenderer from './CheckboxRenderer';
import 'ag-grid/dist/styles/ag-grid.css';
import 'ag-grid/dist/styles/ag-theme-balham.css';
class App extends Component {
constructor(props) {
super(props);
let enableOtherFields = false;
this.state = {
columnDefs: [
{ headerName: 'Make', field: 'make' },
{
headerName: 'noRestrictions', field: 'noRestrictions',
cellRendererFramework: CheckboxRenderer,
cellRendererParams: { checkedVal: true, disable: false },
onCellClicked: function (event) {
// event.node.columnApi.columnController.gridColumns[1].colDef.cellRendererParams.checkedVal=!event.node.columnApi.columnController.gridColumns[1].colDef.cellRendererParams.checkedVal;
// event.node.data.checkbox=!event.data.checkbox;
let currentNode = event.node.id;
event.api.forEachNode((node) => {
if (node.id === currentNode) {
node.data.checkbox = !node.data.checkbox;
}
//if(!node.columnApi.columnController.gridColumns[1].colDef.cellRendererParams.checkedVal){ // checkbox is unchecked
if (node.data.checkbox === false && node.data.checkbox !== 'undefined') {
enableOtherFields = true;
} else {
enableOtherFields = false;
}
//alert(node.id);
//alert(event.colDef.cellRendererParams.checkedVal);
}); alert("enable other fields:" + enableOtherFields);
}
},
{
headerName: 'doNotBuy', field: 'doNotBuy',
cellRendererFramework: CheckboxRenderer,
cellRendererParams: { checkedVal: false, disable: true }
},
{ headerName: 'Price', field: 'price', editable: true }
],
rowData: [
{ make: "Toyota", noRestrictions: true, doNotBuy: false, price: 35000 },
{ make: "Ford", noRestrictions: true, doNotBuy: false, price: 32000 },
{ make: "Porsche", noRestrictions: true, doNotBuy: false, price: 72000 }
]
};
}
componentDidMount() {
}
render() {
return (
<div className= "ag-theme-balham" style = {{ height: '200px', width: '800px' }}>
<AgGridReact enableSorting={ true }
enableFilter = { true}
//pagination={true}
columnDefs = { this.state.columnDefs }
rowData = { this.state.rowData } >
</AgGridReact>
</div>
);
}
}
export default App;
Boolean data in present part:
function booleanCellRenderer(params) {
var valueCleaned = params.value;
if (valueCleaned === 'T') {
return '<input type="checkbox" checked/>';
} else if (valueCleaned === 'F') {
return '<input type="checkbox" unchecked/>';
} else if (params.value !== null && params.value !== undefined) {
return params.value.toString();
} else {
return null;
}
}
var gridOptions = {
...
components: {
booleanCellRenderer: booleanCellRenderer,
}
};
gridOptions.api.setColumnDefs(
colDefs.concat(JSON.parse('[{"headerName":"Name","field":"Field",
"cellRenderer": "booleanCellRenderer"}]')));
Here's a solution that worked for me. It's mandatory to respect arrow functions to solve context issues.
Component:
import React from "react";
class AgGridCheckbox extends React.Component {
state = {isChecked: false};
componentDidMount() {
let boolValue = this.props.value.toString() === "true";
this.setState({isChecked: boolValue});
}
onChanged = () => {
const checked = !this.state.isChecked;
this.setState({isChecked: checked});
this.props.setValue(checked);
};
render() {
return (
<div>
<input type={"checkbox"} checked={this.state.isChecked} onChange={this.onChanged}/>
</div>
);
}
}
export default AgGridCheckbox;
Column definition object inside columnDefs array:
{
headerName: "yourHeaderName",
field: "yourPropertyNameInsideDataObject",
cellRendererFramework: AgGridCheckbox
}
JSX calling ag-grid:
<div
className="ag-theme-balham"
>
<AgGridReact
defaultColDef={defaultColDefs}
columnDefs={columnDefs}
rowData={data}
/>
</div>
I found a good online example for this feature:
https://stackblitz.com/edit/ag-grid-checkbox?embed=1&file=app/ag-grid-checkbox/ag-grid-checkbox.component.html
The background knowledge is based on the cellRendererFramework : https://www.ag-grid.com/javascript-grid-components/
gridOptions = {
onSelectionChanged: (event: any) => {
let rowData = [];
event.api.getSelectedNodes().forEach(node => {
rowDate = [...rowData, node.data];
});
console.log(rowData);
}
}
You can keep a checkbox on display and edit as following:
headerName: 'header name',
field: 'field',
filter: 'agTextColumnFilter',
cellRenderer: params => this.checkBoxCellEditRenderer(params),
And then create an renderer:
checkBoxCellEditRenderer(params) {
const input = document.createElement('input');
input.type = 'checkbox';
input.checked = params.value;
input.addEventListener('click', () => {
params.value = !params.value;
params.node.data[params.coldDef.field] = params.value;
// you can add here code
});
return input;
}
This is an old question but there is a new answer available if you are using AdapTable in conjunction with AG Grid.
Simply define the column as a Checkbox Column and AdapTable will do it all for you - create the checkbox, check it if the cell value is true, and fire an event each time it is checked:
See: https://demo.adaptabletools.com/formatcolumn/aggridcheckboxcolumndemo
So in the end I somewhat got what I wanted, but in a slightly different way, I used popupSelect and cellEditorParams with values: ['true', 'false']. Of course I don't have an actual check box like I wanted, but it behaves good enough for what I need
{
headerName: 'Refunded',
field: 'refunded',
cellEditor: 'popupSelect',
cellEditorParams: {
cellRenderer: RefundedCellRenderer,
values: ['true', 'false']
}
},
function RefundedCellRenderer(params) {
return params.value;
}

bootstrap typeahead url/redirect

$(function(){
var orthoObjs = {};
var orthoNames = [];
var throttledRequest = _.debounce(function(query, process){
$.ajax({
url: 'json/ortho4.json'
,cache: false
,success: function(data){
orthoObjs = {};
orthoNames = [];
_.each( data, function(item, ix, list){
orthoNames.push( item.searchPhr );
orthoObjs[ item.searchPhr ] = item;
});
process( orthoNames );
}
});
}, 300);
$(".typeahead").typeahead({
source: function ( query, process ) {
throttledRequest( query, process );
}
,updater: function (item) {
var url = "orthoObjs[item.searchUrl]";
window.location = url;
Whats the best way to get the redirect to work? I have seen similar questions, but can't get this to work. Documentation on typeahead isn't great. I am using underscore.js for the each function. Just want a simple search query that redirects when the user selects.
I actually got this to work. I got a little help... but here it is. There is the JSON file..
[
{ "id":1, "searchUrl":"invisalign.html", "name":"invisalign" }
,{ "id":2, "searchUrl":"invisalign.html", "name":"invisalign teen" }
,{ "id":3, "searchUrl":"clearbraces.html", "name":"clear braces" }
]
And the HTML code....
Lots of good stuff here.. http://fusiongrokker.com/post/heavily-customizing-a-bootstrap-typeahead
And the search code..
<form method="post" id="myForm" class="navbar-search pull-left">
<input
type="text"
class="search-query typeahead"
placeholder="Search Our Website"
autocomplete="off"
data-provide="typeahead"
/>
<i class="fa-icon-search icon-black"></i>
</form> </li>
$(function(){
var bondObjs = {};
var bondNames = [];
$(".typeahead").typeahead({
source: function ( query, process ) {
//get the data to populate the typeahead (plus an id value)
$.ajax({
url: '/json/bonds.json'
,cache: false
,success: function(data){
bondObjs = {};
bondNames = [];
_.each( data, function(item, ix, list){
bondNames.push( item.name );
bondObjs[ item.name ] = item.searchUrl;
});
process( bondNames );
}
});
}
, updater: function ( selectedName ) {
window.location.href =bondObjs[ selectedName ];
}
});
});
</script>

alert() message isn't being called in my form

Firebug is giving me no error messages, but it's not working. The idea is regardless of whether the user picks an option from dropdown or if they type in something in search box, I want the alert() message defined below to alert what the value of the variable result is (e.g. {filter: Germany}). And it doesn't. I think the javascript breaks down right when a new Form instance is instantiated because I tried putting an alert in the Form variable and it was never triggered. Note that everything that pertains to this issue occurs when form.calculation() is called.
markup:
<fieldset>
<select name="filter" alter-data="dropFilter">
<option>Germany</option>
<option>Ukraine</option>
<option>Estonia</option>
</select>
<input type="text" alter-data="searchFilter" />
</fieldset>
javascript (below the body tag)
<script>
(function($){
var listview = $('#listview');
var lists = (function(){
var criteria = {
dropFilter: {
insert: function(value){
if(value)
return handleFilter("filter", value);
},
msg: "Filtering..."
},
searchFilter: {
insert: function(value){
if(value)
return handleFilter("search", value);
},
msg: "Searching..."
}
}
var handleFilter = function(key,value){
return {key: value};
}
return {
create: function(component){
var component = component.href.substring(component.href.lastIndexOf('#') + 1);
return component;
},
setDefaults: function(component){
var parameter = {};
switch(component){
case "sites":
parameter = {
'order': 'site_num',
'per_page': '20',
'url': 'sites'
}
}
return parameter;
},
getCriteria: function(criterion){
return criteria[criterion];
},
addCriteria: function(criterion, method){
criteria[criterion] = method;
}
}
})();
var Form = function(form){
var fields = [];
$(form[0].elements).each(function(){
var field = $(this);
if(typeof field.attr('alter-data') !== 'undefined') fields.push(new Field(field));
})
}
Form.prototype = {
initiate: function(){
for(field in this.fields){
this.fields[field].calculate();
}
},
isCalculable: function(){
for(field in this.fields){
if(!this.fields[field].alterData){
return false;
}
}
return true;
}
}
var Field = function(field){
this.field = field;
this.alterData = false;
this.attach("change");
this.attach("keyup");
}
Field.prototype = {
attach: function(event){
var obj = this;
if(event == "change"){
obj.field.bind("change", function(){
return obj.calculate();
})
}
if(event == "keyup"){
obj.field.bind("keyup", function(e){
return obj.calculate();
})
}
},
calculate: function(){
var obj = this,
field = obj.field,
msgClass = "msgClass",
msgList = $(document.createElement("ul")).addClass("msgClass"),
types = field.attr("alter-data").split(" "),
container = field.parent(),
messages = [];
field.next(".msgClass").remove();
for(var type in types){
var criterion = lists.getCriteria(types[type]);
if(field.val()){
var result = criterion.insert(field.val());
container.addClass("waitingMsg");
messages.push(criterion.msg);
obj.alterData = true;
alert(result);
initializeTable(result);
}
else {
return false;
obj.alterData = false;
}
}
if(messages.length){
for(msg in messages){
msgList.append("<li>" + messages[msg] + "</li");
}
}
else{
msgList.remove();
}
}
}
$('#dashboard a').click(function(){
var currentComponent = lists.create(this);
var custom = lists.setDefaults(currentComponent);
initializeTable(custom);
});
var initializeTable = function(custom){
var defaults = {};
var custom = custom || {};
var query_string = $.extend(defaults, custom);
var params = [];
$.each(query_string, function(key,value){
params += key + ': ' + value;
})
var url = custom['url'];
$.ajax({
type: 'GET',
url: '/' + url,
data: params,
dataType: 'html',
error: function(){},
beforeSend: function(){},
complete: function() {},
success: function(response) {
listview.html(response);
}
})
}
$.extend($.fn, {
calculation: function(){
var formReady = new Form($(this));
if(formReady.isCalculable) {
formReady.initiate();
}
}
})
var form = $('fieldset');
form.calculation();
})(jQuery)
Thank you for anyone who responds. I spent a lot of time trying to make this work.
The initial problem as to why the alert() was not being triggered when Form is instantiated is because, as you can see, the elements property belongs to the Form object, not fieldset object. And as you can see in the html, I place the fields as descendents of the fieldset object, not form.