Kendo Mobile Appended form elements from treeview not being noticed - kendo-ui

I am trying to figure out why appended form elements are not being notice by kendo mobile --- i have tried 10 different fixes but those items just dont get noticed:
This is in the view:
<li>
<div id="currentMovements">
<ul id="curMoves" data-role="listview" ></ul>
</div>
Add Movements:
<div id="routineMovements"></div>
</li>
And this is my script:
<script>
//init move count
var move_count = 0;
function onSelect(e) {
console.log("Selected: " + this.text(e.node));
//add li to movements div
//make each field unique by li
//using move_count
$("#currentMovements ul").append('<li><input type="text" name="moves[' + move_count + ']" data-min="true" id="moves[' + move_count + ']" class="k-input small-move" value="' + this.text(e.node) + '" /><input type="text" name="id[' + move_count + ']" data-min="true" id="sets[' + move_count + ']" class="k-input small-nums" value="3" /> sets of <input type="text" name="reps[' + move_count + ']" data-min="true" id="reps[' + move_count + ']" class="k-input small-nums" value="10" /><span class="clearitem">Delete</span></li>');
//increase move count
move_count++;
///test to see if the field is being noticed
moves = $('#moves[0]').val();
console.log(moves);
}
function populateRoutineForm() {
$('#curMoves .clearitem').live('click', function() {
$(this).parent().remove();
});
var routineMovementsData = new kendo.data.HierarchicalDataSource({
data: [
{
text: "Chest", items: [
{ text: "Inclined Bench" },
{ text: "Decline Bench" },
{ text: "Dumbell Presses" }
]
},{
text: "Tricep", items: [
{ text: "Cable Pulldowns" },
{ text: "Skull Crushers" },
{ text: "Close Grip Benchpress" }
]
}
]
});
//todo can we use the MVVM stuf from above to do this now?
$("#routineMovements").kendoTreeView({
dataSource: routineMovementsData,
select: onSelect
});
}
function sendAddRoutine() {
var userID = window.localStorage.getItem("userID");
var routine_title = $('#routine_title').val();
var routine_share = $('#routine_share').val();
///test to see if the field is being noticed
moves = $('#moves[0]').val();
console.log(moves);
$.ajax({
url: endpoint + "app/api/add_routine.php",
dataType: "jsonp",
type: "GET",
data: { userID: userID, routine_title: routine_title, routine_share: routine_share },
success: function (data) {
$('#routineResult').html(data.results);
//app.navigate("#view-routineFeed");
}
});
}
$('#routineDoneButton').click(function () {
sendAddRoutine();
});
</script>
Im wondering if there some way to re-init the view without losing other fields that appear above the append div?

Related

Laravel 9 passing data to Javascript file

I want to pass the data from the Laravel controller to the JS file then show it in the Laravel Blade view as it appears in the code
in this var dtUserTable = $('.user-list-table'),
user-list-table is a class that is called on the blade.php page. As it appears this is the call of it, how can I return the data from or pass the data from the Laravel controller to the JS file then show it in the blade.php file?
app-user-list.js
$(function () {
'use strict';
var dtUserTable = $('.user-list-table'),
newUserSidebar = $('.new-user-modal'),
newUserForm = $('.add-new-user'),
statusObj = {
1: { title: 'Pending', class: 'badge-light-warning' },
2: { title: 'Active', class: 'badge-light-success' },
3: { title: 'Inactive', class: 'badge-light-secondary' }
};
var assetPath = '../../../app-assets/',
userView = 'app-user-view.html',
userEdit = 'app-user-edit.html';
if ($('body').attr('data-framework') === 'laravel') {
assetPath = $('body').attr('data-asset-path');
userView = assetPath + 'app/user/view';
userEdit = assetPath + 'app/user/edit';
}
// Users List datatable
if (dtUserTable.length) {
dtUserTable.DataTable({
ajax: assetPath + 'data/user-list.json', // JSON file to add data
columns: [
// columns according to JSON
{ data: 'responsive_id' },
{ data: 'full_name' },
{ data: 'email' },
{ data: 'role' },
{ data: 'current_plan' },
{ data: 'status' },
{ data: '' }
],
columnDefs: [
{
// For Responsive
className: 'control',
orderable: false,
responsivePriority: 2,
targets: 0
},
{
// User full name and username
targets: 1,
responsivePriority: 4,
render: function (data, type, full, meta) {
var $name = full['full_name'],
$uname = full['username'],
$image = full['avatar'];
if ($image) {
// For Avatar image
var $output =
'<img src="' + assetPath + 'images/avatars/' + $image + '" alt="Avatar" height="32" width="32">';
} else {
// For Avatar badge
var stateNum = Math.floor(Math.random() * 6) + 1;
var states = ['success', 'danger', 'warning', 'info', 'dark', 'primary', 'secondary'];
var $state = states[stateNum],
$name = full['full_name'],
$initials = $name.match(/\b\w/g) || [];
$initials = (($initials.shift() || '') + ($initials.pop() || '')).toUpperCase();
$output = '<span class="avatar-content">' + $initials + '</span>';
}
var colorClass = $image === '' ? ' bg-light-' + $state + ' ' : '';
// Creates full output for row
var $row_output =
'<div class="d-flex justify-content-left align-items-center">' +
'<div class="avatar-wrapper">' +
'<div class="avatar ' +
colorClass +
' mr-1">' +
$output +
'</div>' +
'</div>' +
'<div class="d-flex flex-column">' +
'<a href="' +
userView +
'" class="user_name text-truncate"><span class="font-weight-bold">' +
$name +
'</span></a>' +
'<small class="emp_post text-muted">#' +
$uname +
'</small>' +
'</div>' +
'</div>';
return $row_output;
}
},
{
// User Role
targets: 3,
render: function (data, type, full, meta) {
var $role = full['role'];
var roleBadgeObj = {
Subscriber: feather.icons['user'].toSvg({ class: 'font-medium-3 text-primary mr-50' }),
Author: feather.icons['settings'].toSvg({ class: 'font-medium-3 text-warning mr-50' }),
Maintainer: feather.icons['database'].toSvg({ class: 'font-medium-3 text-success mr-50' }),
Editor: feather.icons['edit-2'].toSvg({ class: 'font-medium-3 text-info mr-50' }),
Admin: feather.icons['slack'].toSvg({ class: 'font-medium-3 text-danger mr-50' })
};
return "<span class='text-truncate align-middle'>" + roleBadgeObj[$role] + $role + '</span>';
}
},
{
// User Status
targets: 5,
render: function (data, type, full, meta) {
var $status = full['status'];
return (
'<span class="badge badge-pill ' +
statusObj[$status].class +
'" text-capitalized>' +
statusObj[$status].title +
'</span>'
);
}
},
{
// Actions
targets: -1,
title: 'Actions',
orderable: false,
render: function (data, type, full, meta) {
return (
'<div class="btn-group">' +
'<a class="btn btn-sm dropdown-toggle hide-arrow" data-toggle="dropdown">' +
feather.icons['more-vertical'].toSvg({ class: 'font-small-4' }) +
'</a>' +
'<div class="dropdown-menu dropdown-menu-right">' +
'<a href="' +
userView +
'" class="dropdown-item">' +
feather.icons['file-text'].toSvg({ class: 'font-small-4 mr-50' }) +
'Details</a>' +
'<a href="' +
userEdit +
'" class="dropdown-item">' +
feather.icons['archive'].toSvg({ class: 'font-small-4 mr-50' }) +
'Edit</a>' +
'<a href="javascript:;" class="dropdown-item delete-record">' +
feather.icons['trash-2'].toSvg({ class: 'font-small-4 mr-50' }) +
'Delete</a></div>' +
'</div>' +
'</div>'
);
}
}
],
order: [[2, 'desc']],
dom:
'<"d-flex justify-content-between align-items-center header-actions mx-1 row mt-75"' +
'<"col-lg-12 col-xl-6" l>' +
'<"col-lg-12 col-xl-6 pl-xl-75 pl-0"<"dt-action-buttons text-xl-right text-lg-left text-md-right text-left d-flex align-items-center justify-content-lg-end align-items-center flex-sm-nowrap flex-wrap mr-1"<"mr-1"f>B>>' +
'>t' +
'<"d-flex justify-content-between mx-2 row mb-1"' +
'<"col-sm-12 col-md-6"i>' +
'<"col-sm-12 col-md-6"p>' +
'>',
language: {
sLengthMenu: 'Show _MENU_',
search: 'Search',
searchPlaceholder: 'Search..'
},
// Buttons with Dropdown
buttons: [
{
text: 'Add New User',
className: 'add-new btn btn-primary mt-50',
attr: {
'data-toggle': 'modal',
'data-target': '#modals-slide-in'
},
init: function (api, node, config) {
$(node).removeClass('btn-secondary');
}
}
],
// For responsive popup
responsive: {
details: {
display: $.fn.dataTable.Responsive.display.modal({
header: function (row) {
var data = row.data();
return 'Details of ' + data['full_name'];
}
}),
type: 'column',
renderer: $.fn.dataTable.Responsive.renderer.tableAll({
tableClass: 'table',
columnDefs: [
{
targets: 2,
visible: false
},
{
targets: 3,
visible: false
}
]
})
}
},
language: {
paginate: {
// remove previous & next text from pagination
previous: ' ',
next: ' '
}
},
initComplete: function () {
// Adding role filter once table initialized
this.api()
.columns(3)
.every(function () {
var column = this;
var select = $(
'<select id="UserRole" class="form-control text-capitalize mb-md-0 mb-2"><option value=""> Select Role </option></select>'
)
.appendTo('.user_role')
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? '^' + val + '$' : '', true, false).draw();
});
column
.data()
.unique()
.sort()
.each(function (d, j) {
select.append('<option value="' + d + '" class="text-capitalize">' + d + '</option>');
});
});
// Adding plan filter once table initialized
this.api()
.columns(4)
.every(function () {
var column = this;
var select = $(
'<select id="UserPlan" class="form-control text-capitalize mb-md-0 mb-2"><option value=""> Select Plan </option></select>'
)
.appendTo('.user_plan')
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? '^' + val + '$' : '', true, false).draw();
});
column
.data()
.unique()
.sort()
.each(function (d, j) {
select.append('<option value="' + d + '" class="text-capitalize">' + d + '</option>');
});
});
// Adding status filter once table initialized
this.api()
.columns(5)
.every(function () {
var column = this;
var select = $(
'<select id="FilterTransaction" class="form-control text-capitalize mb-md-0 mb-2xx"><option value=""> Select Status </option></select>'
)
.appendTo('.user_status')
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? '^' + val + '$' : '', true, false).draw();
});
column
.data()
.unique()
.sort()
.each(function (d, j) {
select.append(
'<option value="' +
statusObj[d].title +
'" class="text-capitalize">' +
statusObj[d].title +
'</option>'
);
});
});
}
});
}
// Check Validity
function checkValidity(el) {
if (el.validate().checkForm()) {
submitBtn.attr('disabled', false);
} else {
submitBtn.attr('disabled', true);
}
}
// Form Validation
if (newUserForm.length) {
newUserForm.validate({
errorClass: 'error',
rules: {
'user-fullname': {
required: true
},
'user-name': {
required: true
},
'user-email': {
required: true
}
}
});
newUserForm.on('submit', function (e) {
var isValid = newUserForm.valid();
e.preventDefault();
if (isValid) {
newUserSidebar.modal('hide');
}
});
}
// To initialize tooltip with body container
$('body').tooltip({
selector: '[data-toggle="tooltip"]',
container: 'body'
});
});
Blade/View
#extends('panel.index')
#section('css-con')
<!-- BEGIN: Vendor CSS-->
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/vendors/css/tables/datatable/dataTables.bootstrap4.min.css')}}">
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/vendors/css/tables/datatable/responsive.bootstrap4.min.css')}}">
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/vendors/css/tables/datatable/buttons.bootstrap4.min.css')}}">
<!-- END: Vendor CSS-->
<!-- BEGIN: Page CSS-->
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/css/plugins/forms/form-validation.css')}}">
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/css/pages/app-user.css')}}">
<!-- END: Page CSS-->
#endsection
#section('content')
<!-- users list start -->
<section class="app-user-list">
<!-- users filter start -->
<div class="card">
<h5 class="card-header">Search Filter</h5>
<div class="d-flex justify-content-between align-items-center mx-50 row pt-0 pb-2">
<div class="col-md-4 user_role"></div>
<div class="col-md-4 user_plan"></div>
<div class="col-md-4 user_status"></div>
</div>
</div>
<!-- users filter end -->
<!-- list section start -->
<div class="card">
<div class="card-datatable table-responsive pt-0">
<table class="user-list-table table">
<thead class="thead-light">
<tr>
<th></th>
<th>User</th>
<th>Email</th>
<th>Role</th>
<th>Plan</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
</table>
</div>
<!-- Modal to add new user starts-->
<div class="modal modal-slide-in new-user-modal fade" id="modals-slide-in">
<div class="modal-dialog">
<form class="add-new-user modal-content pt-0">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>
<div class="modal-header mb-1">
<h5 class="modal-title" id="exampleModalLabel">New User</h5>
</div>
<div class="modal-body flex-grow-1">
<div class="form-group">
<label class="form-label" for="basic-icon-default-fullname">Full Name</label>
<input type="text" class="form-control dt-full-name" id="basic-icon-default-fullname" placeholder="John Doe" name="user-fullname" aria-label="John Doe" aria-describedby="basic-icon-default-fullname2" />
</div>
<div class="form-group">
<label class="form-label" for="basic-icon-default-uname">Username</label>
<input type="text" id="basic-icon-default-uname" class="form-control dt-uname" placeholder="Web Developer" aria-label="jdoe1" aria-describedby="basic-icon-default-uname2" name="user-name" />
</div>
<div class="form-group">
<label class="form-label" for="basic-icon-default-email">Email</label>
<input type="text" id="basic-icon-default-email" class="form-control dt-email" placeholder="john.doe#example.com" aria-label="john.doe#example.com" aria-describedby="basic-icon-default-email2" name="user-email" />
<small class="form-text text-muted"> You can use letters, numbers & periods </small>
</div>
<div class="form-group">
<label class="form-label" for="user-role">User Role</label>
<select id="user-role" class="form-control">
<option value="subscriber">Subscriber</option>
<option value="editor">Editor</option>
<option value="maintainer">Maintainer</option>
<option value="author">Author</option>
<option value="admin">Admin</option>
</select>
</div>
<button type="submit" class="btn btn-primary mr-1 data-submit">Submit</button>
<button type="reset" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
<!-- Modal to add new user Ends-->
</div>
<!-- list section end -->
</section>
<!-- users list ends -->
#endsection
#section('jc-con')
<!-- BEGIN: Page Vendor JS-->
<script src="{{asset('app-assets/vendors/js/tables/datatable/jquery.dataTables.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/datatables.bootstrap4.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/dataTables.responsive.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/responsive.bootstrap4.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/datatables.buttons.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/buttons.bootstrap4.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/forms/validation/jquery.validate.min.js')}}"></script>
<!-- END: Page Vendor JS-->
<!-- BEGIN: Page JS-->
<script src="{{asset('app-assets/js/scripts/pages/app-user-list.js')}}"></script>
<!-- END: Page JS-->
#endsection
Below is the function that I call when I want to get the data in the Laravel controller.
public function list()
{
$data = DB::table('users')->get();
return view('content.apps.user.user-list',compact('data'));
}
blade
#push('scripts')
<script>
//line chart
var line = new Morris.Line({
element: 'line-chart',
resize: true,
data: [
#foreach ($data as $value)
{
ym: "{{ $value->year }}-{{ $value->month }}", sum: "{{ $value->sum }}"
},
#endforeach
],
xkey: 'ym',
ykeys: ['sum'],
labels: ['#lang('site.total')'],
lineWidth: 2,
gridTextFamily: 'Open Sans',
gridTextSize: 10
});
</script>
#endpush

hide bootstrap modal after select redirect instead

I would like to close my modalbox, so I return to the same page, after I click the "Select" button.
I am on shuffle.php. I open the modalbox and call the code in updaterecords.php. When I click Select I should return to shuffle.php. The problem is right now that I am redirected to updaterecords.php.
I try to solve that with adding this code to my AJAX call:
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
But I am still redirected. Is the code I added in the wrong place?
shuffle.php
<div class="modal-footer msg">
<form action="updaterecords.php" method="post">
<input type="hidden" id="fantasy-id" value="" name="id" />
<button type="submit" name="selectStore" >Select</button>
<button type="button" data-dismiss="modal">Close</button>
</form>
</div>
updaterecords.php
$(document).ready(function() {
$(".btn-open-modal").click(function() {
var id = $(this).data("id");
$.ajax({
type: 'post',
url: 'getdata.php',
data: {
post_id: id
},
success: function(data) {
console.log(data);
var jdata = JSON.parse(data);
if (jdata) {
console.log("is json");
$("#editBox").modal().show();
$('#id').val(jdata.id);
$("#editBox .modal-title").html(jdata.headline);
$("#editBox .modal-body").html("Weekday: " + jdata.weekday + "<br><br>Description: " + jdata.description); // + " " + $query $query => query
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
} else {
console.log("not valid json: " + data);
}
}
});
});
});
Please try to use $('.modal').modal('hide'); on updaterecords.php.
$(document).ready(function() {
$(".btn-open-modal").click(function() {
var id = $(this).data("id");
$('.modal').modal('hide');
$.ajax({
type: 'post',
url: 'getdata.php',
data: {
post_id: id
},
success: function(data) {
console.log(data);
var jdata = JSON.parse(data);
if (jdata) {
console.log("is json");
$("#editBox").modal().show();
$('#id').val(jdata.id);
$("#editBox .modal-title").html(jdata.headline);
$("#editBox .modal-body").html("Weekday: " + jdata.weekday + "<br><br>Description: " + jdata.description); // + " " + $query $query => query
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
} else {
console.log("not valid json: " + data);
}
}
});
});
});

How to allow ajax form submit on each click?

I noticed that my ajax form can submit twice at the most, meaning once I submit and retrieve data and want to submit the form again to refine search(it's a search form) it can do it. More than twice it cannot submit, the submit button also becomes disabled. Is there any restriction on ajax form to get submitted multiple times?
My form submission is trigered by
$("form").on("submit", function () ...
ajax:
var getData;
$("form").on("submit", function () {
//$(this).find(':submit').attr('disabled','disabled');
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php",
data: data,
success: function (data) {
getData=data;
//$("#main_content").slideUp("normal",function(){
$(".the-return").show();
if(data!=""){
console.log(data.length);
for (i = 0; i < data.length; i++) {
//availability
if(data[i].weekM==0)
{
var avail="Not available";
}
else
{
avail="Available";
}
if(data[i].endA==0)
{
var avail2="Not available";
}
else
{
avail2="Available";
}
if(data[i].weekE==0)
{
var avail3="Not available";
}
else
{
avail3="Available";
}
$(".the-inner-return").append("<div class='inside_return'><section class='row'><div class='small-10 medium-10 large-8 small-centered medium-centered large-centered columns d_result'><div class='text-center post_id'>" + data[i].id +"</div><div class='small-12 medium-12 large-9 columns subject'>"+ data[i].subject+" Instructor</div><div class='small-12 meidum-12 large-3 columns rate'>" + data[i].rate +"</div><span class='hourly'>hourly</span><div class='small-12 medium-12 large-12 text-center name'>" + data[i].name +"</div><div class='small-12 medium-12 large-4 columns plusneg'><img src='img/happy.png'>" + data[i].plus+"<br/><img src='img/sad.png'>"+ data[i].neg+"</div><div class='small-12 medium-12 large-4 columns gender text-center'>Male<br/>Availabiliy:<br/>Mornings:<span class='avail'>" + avail+"</span><br/>Afternoons:<br/><span class='avail'>"+ avail2+"</span><br/>Evening:<span class='avail'>"+ avail3+"</span></div><div class='small-12 medium-12 large-4 columns score text-center'><h6>Reputation score</h6>"+ data[i].reputation+"</div><div class='row'><div class='small-12 medium-12 large-5 columns shortlist text-center'>Add to Shorlist</div><div class='small-12 medium-12 large-5 columns gettutor text-center'>Get Tutor</div></div><div class='small-12 medium-12 large-12 columns text-center date'>Posted on:<span class='elec'>"+ data[i].postDate+"</span></div></div></section></div>");
//alert(data[i].name)
}
}else{
$(".the-return").hide();
$("#the-return-fail").show();
}
//});//closes #main_content
}
});
return false;
});
There is no counter that prevents multiple ajax submissions. However, if you are attempting to submit before the previous request is complete then you probably are going to have problems if you use global variables.
Here's an example that does multiple submissions.
<form action="" method="post">
<input name="foo" id="foo" type="text" />
<button>Send It</button>
</form>
<div id="output">
</div>
The data here is formatted for JSFiddle's echo service
$("form").on("submit", function(event) {
event.preventDefault();
// prevent next submission before request is complete
$("button").prop("disabled", true);
var dt = new Date();
$.ajax({
url: "/echo/json/",
method: "post",
data: {
json: JSON.stringify({
date: new Date(),
foo: $("#foo").val()
}),
delay: 3
},
success: function(result) {
$("#output").append($("<div>").html(result.foo + " " + result.date));
$("button").prop("disabled", false);
}
});
});

Kendo UI : Autocomplete Template Header

I'm new to Kendo UI. I can't figure out why my autocomplete is not showing the header template.The row template is working fine. I looked at the example and I'm not sure what I'm doing differently
Here is my JavaScript code:
<script>
$(document).ready(function () {
$("#drug_name").kendoAutoComplete({
dataTextField: "name",
change: function (e) {
if ($("#drug_name").val() == "") {
$("#dose").val("");
$("#unit").val("");
$("#route").val("");
}
},
select: function (e) {
var dataItem = this.dataItem(e.item.index());
$("#dose").val(dataItem.dose);
$("#unit").val(dataItem.unit);
$("#route").val(dataItem.route);
//output selected dataItem
console.log(kendo.stringify(dataItem));
},
headerTemplate: '<div class="dropdown-header"><span class="k-widget k-header">Name</span><span class="k-widget k-header">Route</span><span class="k-widget k-header">Dose</span><span class="k-widget k-header">Unit</span></div>',
template: '<span class="k-state-default">#:data.name#</span><span class="k-state-default">#:data.route#</span><span class="k-state-default">#:data.dose#</span><span class="k-state-default">#:data.unit#</span>',
filter: "contains",
minLength: 3,
dataSource: {
serverFiltering: true,
transport: {
read: { url: "/Medication/Load", dataType: "json" },
parameterMap: function (data, action) {
if (action === "read") {
return {
medicationName: data.filter.filters[0].value
};
} else {
return data;
}
}
}
},
height: 370
});
});
Please try to write like this:
headerTemplate: '<div class="dropdown-header">' + '<span class="k-widget k-header">Name</span>' + '<span class="k-widget k-header">Route</span>' + '<span class="k-widget k-header">Dose</span>' + <span class="k-widget k-header">Unit</span>' + '</div>',

How to programatically expand a node of Kendo treeview

I have a Kendo treeview that is built as below codes (see below). Each tree node has a unique data id field (that is employee Id).
I would like to have a text box ( <input type="text" ... /> ) and a button ( <input type="button" ... /> ) so user can input some id and when she hit the button, the button click event handler will let the treeview expand the node whose id matches the input id. How can I do that? Thank you very much.
Details of click event handler or the button:
function buttonExpand_onClick()
{
var id = $("textboxEmployeeId").val();
// ???
// how can I do the following code lines to expand the node with id of "id" to see all its children?
}
Details of the existing Kendo treeview building codes:
<div id="treeviewEmployee">
</div>
<script id="treeview-template" type="text/kendo-ui-template">
#: item.text #
</script>
$(function(
{
var defaultRootSelectedId = 1; // 1 is employee id of the root employee on first loading
$.ajax({
url: '/Employee/AjaxGetEmployeeNodes/?id=' + defaultRootSelectedId,
type: 'GET',
dataType: 'json',
async: false,
success: function (data, textStatus, xhr) {
$("#reeviewEmployee").kendoTreeView({
template: kendo.template($("#treeview-template").html()),
dataSource: data,
select: treeview_onSelect
});
_treeview = $("#treeviewEmployee").data("kendoTreeView");
},
error:
function (xhr, textStatus, errorThrown) {
alert(textStatus);
}
});
});
You can access the datasource on the treeview and find the node by id. I would also like to add that the treeView has a 'findByText()' method as well, in case that is what you want.
HTML
<script id="treeTemplate" type="text/x-kendo-template">
#: item.text #
</script>
<div id="content">
<div id="form">
<label>Node ID:
<input id="nodeId" type="text"/>
</label>
<button id="expandNodeBtn">Expand Node</button>
</div>
<h2>TreeView</h2>
<div id="treeView"/>
</div>
JAVASCRIPT
(function ($) {
$(document).ready(function () {
$("#treeView").kendoTreeView({
dataSource: [
{
text: 'one with id 1',
id: 1,
items: [
{
text: 'one-child-1',
id: 2
},
{
text: 'one-child-2',
id: 3
}
]
},
{
text: 'two with id 4',
id: 4,
items: [
{
text: 'two-child-1',
id: 5
},
{
text: 'two-child-2',
id: 6
}
]
}
]
});
$("#expandNodeBtn").on("click", function(e) {
var val = $("#nodeId").val();
console.log('val: ' + val);
var treeView = $("#treeView").data('kendoTreeView');
var dataSource = treeView.dataSource;
var dataItem = dataSource.get(val); // find item with id = 5
var node = treeView.findByUid(dataItem.uid);
treeView.expand(node);
});
});
})(jQuery);
JSFiddle
I also put together a JSFiddle sample for you to play with: http://jsfiddle.net/jsonsee/D35Q6/
Slightly related, but I came here looking for an answer to this question: How to expand the whole branch when clicking to a parent node in angular treeview? Since I didnt find any answers, I post my solution here. Hope it helps someone.
html
<div id="treeview" kendo-tree-view="tree" k-options="options" k-on-change="selectItem(dataItem)">
</div>
controller
$scope.options = {
dataSource: dummyData,
template: $scope.treeItemTemplate
}
$scope.treeItemTemplate = "<button ng-click='expandRoot(dataItem)'>Blow up</button>";
$scope.expandRoot = function expandRoot(dataItem) {
dataItem.expanded = true;
if (dataItem.hasChildren) {
dataItem.load()
var children = dataItem.children.data();
children.forEach(function (c) {
c.expanded = true;
$scope.expandRoot(c)
});
}
}

Resources