Following is how I populate my jqTreeView.
View
#Html.Trirand().JQTreeView(
new JQTreeView
{
DataUrl = Url.Action("RenderTree"),
Height = Unit.Pixel(500),
Width = Unit.Pixel(150),
HoverOnMouseOver = false,
MultipleSelect = false,
ClientSideEvents = new TreeViewClientSideEvents()
{
Select="spawnTabAction"
}
},
"treeview"
)
<script>
function spawnTabAction(args, event) {
alert(args);
}
</script>
Controller
public JsonResult RenderTree()
{
var tree = new JQTreeView();
List<JQTreeNode> nodes = new List<JQTreeNode>();
nodes.Add(new LeafNode { Text = "Products", Value="Product/Product/Index" });
FolderNode fNode = new FolderNode { Text = "Customers" };
fNode.Nodes.Add(new LeafNode() { Text = "Today's Customers", Value = "Customer/Customer/Today" });
nodes.Add(fNode);
nodes.Add(new LeafNode { Text = "Suppliers", Value = "Supplier/Supplier/Index" });
nodes.Add(new LeafNode { Text = "Employees", Value = "Employee/Employee/Index" });
nodes.Add(new LeafNode { Text = "Orders", Value = "Order/Order/Index" });
return tree.DataBind(nodes);
}
What I want to do is spawn a tab based on the Value of the selected node. I tried a lot but couldn't get hold of the selected node's value.
Later I checked the DOM of rendered page and found that the value is nowhere added to the node but magically when I select the node the value appears in a hidden control by the name treeview_selectedState (treeview being the id of the control). I even traced all ajax calls but couldn't find anything.
Questions:
1) Where does it keep the Values of tree nodes?
2) How do I get the Selected Node's value in select event?
I even tried to get the treeview_selectedState control's value in select event but it returned [].
Then I added a button the view and hooked that onto a js function and found the value there. It makes me think that the value is not available in select event, am I right in thinking that?
I don't think getting selected node's value should be a this big deal? Am I missing something very obvious?
Thanks,
A
After trying so many things , I checked their demo and found the hints there (I shouldve done this as the first thing).
It was actually pretty straight forward
function spawnTabAction(args, event) {
alert($("#treeview").getTreeViewInstance().getNodeOptions(args).value);
}
Thanks,
A
Related
The Angular Material documentation gives a nice example for how to add selection to a table (Table Selection docs). They even provide a Stackblitz to try it out.
I found in the code for the SelectionModel constructor that the first argument is whether there can be multiple selections made (true) or not (false). The second argument is an array of initially selected values.
In the demo, they don't have any initially selected values, so the second argument in their constructor (line 36) is an empty array ([]).
I want to change it so that there is an initially selected value, so I changed line 36 to:
selection = new SelectionModel<PeriodicElement>(true, [{position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}]);
This changes the checkbox in the header to an indeterminate state (as expected), but does not cause the row in the table to be selected. Am I setting the initial value incorrectly, or what am I missing here? How can I set an initially selected value?
Tricky one. You need to initialize the selection by extracting that particular PeriodicElement object from your dataSource input, and passing it to the constructor.
In this particular case, you could code
selection = new SelectionModel<PeriodicElement>(true, [this.dataSource.data[1]);
It's because of the way SelectionModel checks for active selections.
In your table markup you have
<mat-checkbox ... [checked]="selection.isSelected(row)"></mat-checkbox>
You expect this binding to mark the corresponding row as checked. But the method isSelected(row) won't recognize the object passed in here as being selected, because this is not the object your selection received in its constructor.
"row" points to an object from the actual MatTableDataSource input:
dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
But the selection initialization:
selection = new SelectionModel<PeriodicElement>(true, [{position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}]);
happens with a new object you create on the fly. Your selection remembers THIS object as a selected one.
When angular evaluates the bindings in the markup, SelectionModel internally checks for object identity. It's going to look for the object that "row" points to in the internal set of selected objects.
Compare to lines 99-101 and 16 from the SelectionModel source code:
isSelected(value: T): boolean {
return this._selection.has(value);
}
and
private _selection = new Set<T>();
I was facing the same issue, I used dataSource to set the initial value manually in ngOnInit()
ngOnInit() {
this.dataSource.data.forEach(row => {
if (row.symbol == "H") this.selection.select(row);
});
}
If you do the following, it works too
selection = new SelectionModel<PeriodicElement>(true, [ELEMENT_DATA[1]])
To select all you can do
selection = new SelectionModel<PeriodicElement>(true, [...ELEMENT_DATA])
I hope the answer is helpful
Or more dynamically if you have a set of values and you want to filter them before:
selection = new SelectionModel<PeriodicElement>(true, [
...this.dataSource.data.filter(row => row.weight >= 4.0026)
]);
This gets more tricky if you have data loading asynchronously from an api. Here is how I did it:
Firstly I have implemented the DataSource from "#angular/cdk/table". I also have an RxJS Subject that fires whenever data is loaded (first time or when user changes page in the pagination section)
export abstract class BaseTableDataSource<T> implements DataSource<T>{
private dataSubject = new BehaviorSubject<T[]>([]);
private loadingSubject = new BehaviorSubject<boolean>(false);
private totalRecordsSubject = new BehaviorSubject<number>(null);
public loading$ = this.loadingSubject.asObservable();
public dataLoaded$ = this.dataSubject.asObservable();
public totalRecords$ = this.totalRecordsSubject.asObservable().pipe(filter(v => v != null));
constructor(){}
connect(collectionViewer: CollectionViewer): Observable<T[]>{
return this.dataSubject.asObservable();
}
disconnect(collectionViewer: CollectionViewer): void {
this.dataSubject.complete();
this.loadingSubject.complete();
this.totalRecordsSubject.complete();
}
abstract fetchData(pageIndex, pageSize, ...params:any[]) : Observable<TableData<T>>;
abstract columnMetadata(): {[colName: string]: ColMetadataDescriptor };
loadData(pageIndex, pageSize, params?:any[]): void{
this.loadingSubject.next(true);
this.fetchData(pageIndex, pageSize, params).pipe(
finalize(() => this.loadingSubject.next(false))
)
.subscribe(data => {
this.totalRecordsSubject.next(data.totalNumberOfRecords);
this.dataSubject.next(data.records)
});
}
}
Now when I want to pre-select a row, I can write a function like this in my component which hosts a table that uses an implementation of the above mentioned data source
selectRow(rowSelectionFn: (key: string) => boolean){
this.dataSource.dataLoaded$.pipe(takeUntil(this.destroyed$))
.subscribe(data => {
const foundRecord = data.filter(rec => rowSelectionFn(rec));
if(foundRecord && foundRecord.length >= 0){
this.selection.toggle(foundRecord[0]);
}
});
}
How can I get hold on the <option> that was just selected when listening to the select2:select event? Note that this is simple when using a single-select, as when only one option is selected, that must be the one that was just selected. I would like to also be able to find the option that was just selected when using a multiple-select (<select multiple>).
In the select2:unselect event, the unselected <option> is available through e.params.data.element, but it is not so in the select2:select event. I do not see a reason why the <option> should not be available, since it is created at this time. For the select2:selecting event, however, the <option> is not yet created, and obviously cannot be available when the event is fired.
I've used the following to get the current selected in Select2 (it's for version 4 and up):
// single value
var test = $('#test');
test.on("select2:select", function(event) {
var value = $(event.currentTarget).find("option:selected").val();
console.log(value);
});
UPDATE: Multi Selected Values (with and without last selected)
// multi values, with last selected
var old_values = [];
var test = $("#test");
test.on("select2:select", function(event) {
var values = [];
// copy all option values from selected
$(event.currentTarget).find("option:selected").each(function(i, selected){
values[i] = $(selected).text();
});
// doing a diff of old_values gives the new values selected
var last = $(values).not(old_values).get();
// update old_values for future use
old_values = values;
// output values (all current values selected)
console.log("selected values: ", values);
// output last added value
console.log("last added: ", last);
});
$('#test').on('select2:select', function(e) {
var data = e.params.data;
console.log(data);
});
I'm trying to incorporate a bootstrap toggle into a column of my AwesomeMVC Grid (http://demo.aspnetawesome.com/GridDemo) but the toggle doesn't get rendered correctly even after initializing the bootstrap toggle. This is because the AwesomeMVC grid gets rendered after page load.
I don't want to implement a timeout in initializing the bootstrap toggles as Grid loading times may be different.
Has anyone tried implementing any similar bootstrap plugin with AwesomeMVC?
Here's my code sample.
View
#(Html.Awe().Grid("UserList")
.Url(Url.Action("GetUser", "User"))
.Persistence(Persistence.Local)
.Selectable(SelectionType.None)
.Parent("pagesize", "pagesize")
.Columns(
new Column { Name = "Name", Header = "FullName", Width = 72, SortRank = 1, Sort = Sort.Asc },
new Column { Name = "Active", Header = "Active", Width = 60, ClientFormatFunc = "CustomActive", Group = true}
))
Javascript
//Custom content for Active ClientFormatFunc
var CustomActive = function (GetUserList_Result) {
return "<input type=\"checkbox\" class=\"checkbox-toggle\" data-toggle=\"toggle\" data-on=\"Yes\" data-off=\"No\" data-size=\"small\">";
}
$(function () {
$(".checkbox-toggle").bootstrapToggle();
});
there's the aweload event that you can hook up to, also when you render the checkbox I think you need to set its checked state, so you should end up with something like this:
#(Html.Awe().Grid("UserList")
.Url(Url.Action("GetUser", "User"))
.Persistence(Persistence.Local)
.Parent("pagesize", "pagesize")
.Columns(
new Column { Name = "Name", Header = "FullName"},
new Column { ClientFormatFunc = "CustomActive", Width = 75}))
<script type="text/javascript">
$(function () {
$('#UserList').on('aweload', function () {
$(this).find(".checkbox-toggle").bootstrapToggle();
});
});
//Custom content for Active ClientFormatFunc
var CustomActive = function (model) {
var checked = model.Active ? 'checked = "checked"' : '';
return '<input type="checkbox" ' + checked + ' class="checkbox-toggle" data-toggle="toggle" data-on="Yes" data-off="No" data-size="small">';
};
<script>
I also removed .Selectable(SelectionType.None) because it is like that by default, and also I see that you group by a boolean column (active) not sure if that makes sense, it will just split your grid in 2 groups, Column.Name is not required, it is used for binding to model for sorting/grouping, and it's better to always have at least 1 column without width (if you set width to all columns and the grid width doesn't match they work as percentages)
I am using kendoUI tree view with check boxes implementation.
I am able to check all children's check boxes,when i select the parent checkbox.
now,I want to get all the children's text values when i select the parent check box.
I used template for check box operation in tree view
$("#ProjectUsersTreeView [type=checkbox]").live('change', function (e) { var chkbox = $(this);
var parent = chkbox.parent();
var pBox = $(parent).closest('.k-item').find(":checkbox");
if (this.checked || pBox.length>0) {
$(pBox).prop('checked',this.checked ? "checked": "")
}
Instead of using your code for checking children I do recommend using KendoUI configuration option checkChildren.
tree = $("#ProjectUsersTreeView").kendoTreeView({
checkboxes:{
checkChildren: true
},
...
}).data("kendoTreeView");
Then for getting all selected text use:
$("#ProjectUsersTreeView [type=checkbox]").live('change', function (e) {
var checked = $("input:checked", tree);
$.each(checked, function(idx, elem) {
console.log("text", tree.text(elem));
})
});
In checked I get all input elements from the tree that are actually checked and display its text on console by getting it using text method.
NOTE: Realize that I've defined tree as $("#ProjectUsersTreeView").data("kendoTreeView") and then use it in change handler.
I am trying to process multiple input selects in a form each one has a unique name and id.
here is my first try, this is broken when y = value.val(); executes
var selects = $("#pmWorkOrderProcedureStepsForm").find('select');
$.each(selects,
function(index, value)
{
y = value.val();
});
I can see in chrome debug that value has a reference to something that looks like
HTMLSelectElement#select-choice-400139826
Where select-choice-400139826 is my first select input name.
How do I get just the name and the selected value of the input from here.
New to jquery mobile!
You can use the following code snippet:
var selects = $("#pmWorkOrderProcedureStepsForm").find("select");
$.each(selects,function(){
name = $(this).attr('name');
value = $(this).val();
});
A demo here - http://jsfiddle.net/5xg6F/
Let me know if that helps.