I have array of datasource, and I would like bind by data-bind attribute
<div data-role="listview"
data-template="template3"
data-bind="source: products"></div>
template3:
<script type="text/x-kendo-template" id="template3">
# for (var y = 0; y < data.length; y++) { #
<div data-role="listview"
data-template="template"
data-bind="source: data[y]"></div>
# } #
</script>
viewmodel:
var viewModel = kendo.observable({
products: [new kendo.data.DataSource({
schema: {
model: {
id: "Id"
}
},
transport: {
read: {
url: "#Url.Action("Products", "Home")",
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
}
})]
And I get error:
Uncaught ReferenceError: y is not defined
Why is there an array around your DataSource?
Anyway, the concrete error you're getting is because y is not defined in the context you're trying to access it.
You need to change your template:
# for (var y = 0; y < data.length; y++) { #
<div data-role="listview"
data-template="template"
data-bind="source: data.at(#=y#)"></div>
# } #
Related
I have a lot of problem to upload multiple images using AJAX. I write this code:
HTML
<form id="upload" method="post" enctype="multipart/form-data">
<div id="drop" class="drop-area">
<div class="drop-area-label">
Drop image here
</div>
<input type="file" name="file" id="file" multiple/>
</div>
<ul class="gallery-image-list" id="uploads">
<!-- The file uploads will be shown here -->
</ul>
</form>
<div id="listTable"></div>
jQuery/AJAX
$(document).on("change", "input[name^='file']", function(e){
e.preventDefault();
var This = this,
display = $("#uploads");
// list all file data
$.each(This.files, function(i, obj){
// for each image run script asynchronous
(function(i) {
// get data from input file
var file = This.files[i],
name = file.name,
size = file.size,
type = file.type,
lastModified = file.lastModified,
lastModifiedDate = file.lastModifiedDate,
webkitRelativePath = file.webkitRelativePath,
slice = file.slice,
i = i;
// DEBUG
/*
var acc = []
$.each(file, function(index, value) {
acc.push(index + ": " + value);
});
alert(JSON.stringify(acc));
*/
$.ajax({
url:'/ajax/upload.php',
contentType: "multipart/form-data",
data:{
"image":
{
"name":name,
"size":size,
"type":type,
"lastModified":lastModified,
"lastModifiedDate":lastModifiedDate,
"webkitRelativePath":webkitRelativePath,
//"slice":slice,
}
},
type: "POST",
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
// Check if upload property exists
if(myXhr.upload)
{
// For handling the progress of the upload
myXhr.upload.addEventListener("progress",progressHandlingFunction, false);
}
return myXhr;
},
cache: false,
success : function(data){
// load ajax data
$("#listTable").append(data);
}
});
// display progress
function progressHandlingFunction(e){
if(e.lengthComputable){
var perc = Math.round((e.loaded / e.total)*100);
perc = ( (perc >= 100) ? 100 : ( (perc <= 0) ? 0 : 0 ) );
$("#progress"+i+" > div")
.attr({"aria-valuenow":perc})
.css("width", perc+"%");
}
}
// display list of files
display.append('<li>'+name+'</li><div class="progress" id="progress'+i+'">'
+'<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">'
+'</div></div>');
})(i);
});
});
I've tried a various versions and I never succeed to send multiple data through ajax. I have tried in this way what you see above, and now I get only POST informations. I understand why i get POST but I need to send FILES information and I do not know where I'm wrong.
I not work the first time with ajax and often use it for most projects but I have never used to send multiple files and that bothering me now.
Thanks!
Try utilizing json to upload , process file object
html
<div id="drop" class="drop-area ui-widget-header">
<div class="drop-area-label">Drop image here</div>
</div>
<br />
<form id="upload">
<input type="file" name="file" id="file" multiple="true" accepts="image/*" />
<ul class="gallery-image-list" id="uploads">
<!-- The file uploads will be shown here -->
</ul>
</form>
<div id="listTable"></div>
css
#uploads {
display:block;
position:relative;
}
#uploads li {
list-style:none;
}
#drop {
width: 90%;
height: 100px;
padding: 0.5em;
float: left;
margin: 10px;
border: 8px dotted grey;
}
#drop.hover {
border: 8px dotted green;
}
#drop.err {
border: 8px dotted orangered;
}
js
var display = $("#uploads"); // cache `#uploads`, `this` at `$.ajax()`
var droppable = $("#drop")[0]; // cache `#drop` selector
$.ajaxSetup({
context: display,
contentType: "application/json",
dataType: "json",
beforeSend: function (jqxhr, settings) {
// pre-process `file`
var file = JSON.parse(
decodeURIComponent(settings.data.split(/=/)[1])
);
// add `progress` element for each `file`
var progress = $("<progress />", {
"class": "file-" + (!!$("progress").length
? $("progress").length
: "0"),
"min": 0,
"max": 0,
"value": 0,
"data-name": file.name
});
this.append(progress, file.name + "<br />");
jqxhr.name = progress.attr("class");
}
});
var processFiles = function processFiles(event) {
event.preventDefault();
// process `input[type=file]`, `droppable` `file`
var files = event.target.files || event.dataTransfer.files;
var images = $.map(files, function (file, i) {
var reader = new FileReader();
var dfd = new $.Deferred();
reader.onload = function (e) {
dfd.resolveWith(file, [e.target.result])
};
reader.readAsDataURL(new Blob([file], {
"type": file.type
}));
return dfd.then(function (data) {
return $.ajax({
type: "POST",
url: "/echo/json/",
data: {
"file": JSON.stringify({
"file": data,
"name": this.name,
"size": this.size,
"type": this.type
})
},
xhr: function () {
// do `progress` event stuff
var uploads = this.context;
var progress = this.context.find("progress:last");
var xhrUpload = $.ajaxSettings.xhr();
if (xhrUpload.upload) {
xhrUpload.upload.onprogress = function (evt) {
progress.attr({
"max": evt.total,
"value": evt.loaded
})
};
xhrUpload.upload.onloadend = function (evt) {
var progressData = progress.eq(-1);
console.log(progressData.data("name")
+ " upload complete...");
var img = new Image;
$(img).addClass(progressData.eq(-1)
.attr("class"));
img.onload = function () {
if (this.complete) {
console.log(
progressData.data("name")
+ " preview loading..."
);
};
};
uploads.append("<br /><li>", img, "</li><br />");
};
}
return xhrUpload;
}
})
.then(function (data, textStatus, jqxhr) {
console.log(data)
this.find("img[class=" + jqxhr.name + "]")
.attr("src", data.file)
.before("<span>" + data.name + "</span><br />");
return data
}, function (jqxhr, textStatus, errorThrown) {
console.log(errorThrown);
return errorThrown
});
})
});
$.when.apply(display, images).then(function () {
var result = $.makeArray(arguments);
console.log(result.length, "uploads complete");
}, function err(jqxhr, textStatus, errorThrown) {
console.log(jqxhr, textStatus, errorThrown)
})
};
$(document)
.on("change", "input[name^=file]", processFiles);
// process `droppable` events
droppable.ondragover = function () {
$(this).addClass("hover");
return false;
};
droppable.ondragend = function () {
$(this).removeClass("hover")
return false;
};
droppable.ondrop = function (e) {
$(this).removeClass("hover");
var image = Array.prototype.slice.call(e.dataTransfer.files)
.every(function (img, i) {
return /^image/.test(img.type)
});
e.preventDefault();
// if `file`, file type `image` , process `file`
if (!!e.dataTransfer.files.length && image) {
$(this).find(".drop-area-label")
.css("color", "blue")
.html(function (i, html) {
$(this).delay(3000, "msg").queue("msg", function () {
$(this).css("color", "initial").html(html)
}).dequeue("msg");
return "File dropped, processing file upload...";
});
processFiles(e);
} else {
// if dropped `file` _not_ `image`
$(this)
.removeClass("hover")
.addClass("err")
.find(".drop-area-label")
.css("color", "darkred")
.html(function (i, html) {
$(this).delay(3000, "msg").queue("msg", function () {
$(this).css("color", "initial").html(html)
.parent("#drop").removeClass("err")
}).dequeue("msg");
return "Please drop image file...";
});
};
};
php
<?php
if (isset($_POST["file"])) {
// do php stuff
// call `json_encode` on `file` object
$file = json_encode($_POST["file"]);
// return `file` as `json` string
echo $file;
};
jsfiddle http://jsfiddle.net/guest271314/0hm09yqo/
I use Telerik kendo-tree-view to show popup inside which all parent node is there
as checkbox.So when I should check parent node it should expand and check all child node automatically.But Not happening so and the issue is only for first time from second time working fine.
For first time when i check parent node it gets expand and have all child node but not checked.
Refer the code below
Html part:
<div class="col-md-10 col-sm-10 remove-padding" id="parent">
<div style="height: 300px;overflow-y: auto;border:1px solid black" id="adminTreeView" kendo-tree-view="tree"
k-data-source="rc.adminTreeData"
k-options="rc.adminTreeOptions" tabindex="3">
</div>
</div>
Angular part:
rc.adminTreeOptions = {
dataTextField: 'DisplayName',
checkboxes: {
checkParent:true,
checkChildren: true
},
check: onCheck,
};
rc.GetResourcePermission = function (roleId) {
rc.adminTreeData = new kendo.data.HierarchicalDataSource({
transport: {
read: function (e) {
var id = e.data.Id || 0;
roleService.getHierarchyResourceByParentId(id, roleId, (rc.SelectedClient == '' ? null : rc.SelectedClient), CurrentAppId).then(function (response) {
e.success(response);
});
}
},
schema: {
model: {
id: "Id",
hasChildren: "HasChild"
},
parse: function (response) {
return $.map(response, function (x) {
x.checked = x.Checked;
return x;
});
}
},
requestEnd: function () {
if (roleId != 0) {
if (angular.element("#adminTreeView").data("kendoTreeView") && angular.element("#adminTreeView").data("kendoTreeView").expand) {
angular.element("#adminTreeView").data("kendoTreeView").expand(".k-item");
}
}
},
});
}
I want to change the chart-type based on the drop-down value. I had tried and followed the example but it still unable to work. I'm not sure which part that i had missed. I am using JavaScript Charts & Graphs from JSON Data Using AJAX. The code below:
<script src="../js/custom.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/>
<script>
window.onload = function () {
var dataPoints = [];
$.getJSON( "<?php echo $url; ?>", function( json ) {
for (var i = 0; i < json.dates.length; i++) {
dataPoints.push({
x: new Date(json.dates[i]),
y: json.values[i]
});
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
theme: "dark2",
title: {
text: "REPORT"
},
axisY: {
title: "Qty"
},
data: [{
type: "column",
//indexLabel: "{y}", //Shows y value on all Data Points
yValueFormatString: "#,### Units",
indexLabelFontColor: "#5A5757",
indexLabelPlacement: "outside",
dataPoints: dataPoints
}]
});
chart.render();
})
.done(function(){
alert("Completed");
})
.fail(function(e){
console.log('error:');
console.error(e);
})
.always(function(){
alert("always runs");
});
}
var chartType = document.getElementById('chartType');
chartType.addEventListener( "change", function(){
for(var i = 0; i < chart.options.data.length; i++){
chart.options.data[i].type = chartType.options[chartType.selectedIndex].value;
}
chart.render();
});
</script>
Drop-down list:
<select id="chartType" class="form-control" name="chartType">
<option value="column">Column</option>
<option value="line">Line</option>
<option value="bar">Bar</option>
<option value="pie">Pie</option>
<option value="doughnut">Doughnut</option>
</select>
Thank you in advance.
It just seems like variable scope issue, you are creating chart inside AJAX but trying to access it outside during changing the chart type, it would have thrown error in Browser Console. I would suggest you to do it outside AJAX and update just dataPoints inside AJAX.
Here is the updated / working code (Sample JSON with just 1 dataPoint is stored in: https://api.myjson.com/bins/18hgaa):
var dataPoints = [];
var chart;
$.getJSON("https://api.myjson.com/bins/18hgaa", function(json){
for (var i = 0; i < json.dates.length; i++) {
dataPoints.push({
x: new Date(json.dates[i]),
y: json.values[i]
});
}
}).done(function(){
chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
theme: "dark2",
title: {
text: "REPORT"
},
axisY: {
title: "Qty"
},
data: [{
type: "column",
//indexLabel: "{y}", //Shows y value on all Data Points
yValueFormatString: "#,### Units",
indexLabelFontColor: "#5A5757",
indexLabelPlacement: "outside",
dataPoints: dataPoints
}]
});
chart.render();
});
var chartType = document.getElementById('chartType');
chartType.addEventListener( "change", function(){
for(var i = 0; i < chart.options.data.length; i++){
chart.options.data[i].type = chartType.options[chartType.selectedIndex].value;
}
chart.render();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>
<select id="chartType" class="form-control" name="chartType">
<option value="column">Column</option>
<option value="line">Line</option>
<option value="bar">Bar</option>
<option value="pie">Pie</option>
<option value="doughnut">Doughnut</option>
</select>
I have a Kendo Grid where I bind it dynamically to a JSON object.
In the generateColumns function, I want to call the getKendoColor function. However, I need to pass the column cell value. In the code below I forced in 'RED' to show how it should work.
How do I pass in the column value to this getKendoColor function?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.common.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.rtl.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.silver.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.mobile.all.min.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.3.913/js/kendo.all.min.js"></script>
</head>
<body>
<div id="grid" style="width:1000px;"></div>
<script>
var isDateField =[];
var isTaskField =[];
$.ajax({
url: "http://www.mocky.io/v2/59c4dd1e4000005400b25ba7",
dataType: "jsonp",
success: function(result) {
generateGrid(result);
}
});
function generateGrid(response) {
var model = generateModel(response);
var columns = generateColumns(response);
var grid = $("#grid").kendoGrid({
dataSource: {
transport:{
read: function(options){
options.success(response.Table);
}
},
pageSize: 5,
schema: {
model: model
}
},
columns: columns,
pageable: true,
editable:false
});
}
function generateColumns(response) {
var columnNames = response["columns"];
return columnNames.map(function (name) {
if (isTaskField[name]) {
return { field: name, template: '#= getKendoColor("RED") #', format: (isDateField[name] ? "{0:D}" : "") };
}
else
return { field: name, format: (isDateField[name] ? "{0:D}" : "") };
})
}
function generateModel(response) {
var sampleDataItem = response["Table"][0];
var model = {};
var fields = {};
for (var property in sampleDataItem) {
var itemValue = sampleDataItem[property];
if (property.indexOf("ID") !== -1) {
model["id"] = property;
}
var propType = typeof sampleDataItem[property];
if (propType === "number") {
fields[property] = {
type: "number",
validation: {
required: true
}
};
if (model.id === property) {
fields[property].editable = false;
fields[property].validation.required = false;
}
} else if (propType === "boolean") {
fields[property] = {
type: "boolean"
};
} else if (propType === "string") {
var parsedDate = kendo.parseDate(sampleDataItem[property]);
if (parsedDate) {
fields[property] = {
type: "date",
validation: {
required: true
}
};
isDateField[property] = true;
} else {
fields[property] = {
validation: {
required: true
}
};
if ((property !== "Entity") && (property !== "Period") && (property !== "Level"))
{
isTaskField[property] = true;
}
}
} else {
fields[property] = {
validation: {
required: true
}
};
}
}
model.fields = fields;
return model;
}
function getKendoColor(OverallStatus) {
OverallStatus = OverallStatus.toUpperCase();
//alert(OverallStatus);
var htmlRed = kendo.format('<div class="text-center"><div style="color:red"> <i class="fa fa-circle fa-lg"></i> </div> </div>');
var htmlGreen = kendo.format('<div class="text-center"><div style="color:green"> <i class="fa fa-circle fa-lg"></i> </div> </div>');
var htmlOrange = kendo.format('<div class="text-center"><div style="color:orange"> <i class="fa fa-circle fa-lg"></i> </div> </div>');
var htmlYellow = kendo.format('<div class="text-center"><div style="color:yellow"> <i class="fa fa-circle fa-lg"></i> </div> </div>');
switch (OverallStatus) {
case "RED":
return htmlRed;
case "GREEN":
return htmlGreen;
case "ORANGE":
return htmlOrange;
case "YELLOW":
return htmlYellow;
case "CREATED":
return htmlRed;
case "APPROVED":
return htmlGreen;
}
}
</script>
</body>
</html>
https://dojo.telerik.com/AgALaK/2
You can set the template itself as a function and in your case, a slight change to getKendoColor will do the trick:
function getColumnTemplate(dataItem) {
var OverallStatus = dataItem.OverallStatus.toUpperCase();
//All the rest of your getKendoColor function
return someHTML;
}
Then just use this function as the template.
return columnNames.map(function (name) {
if (isTaskField[name]) {
return { field: name, template: getColumnTemplate, format: (isDateField[name] ? "{0:D}" : "") };
}
else
return { field: name, format: (isDateField[name] ? "{0:D}" : "") };
})
I am trying to fill auto complete textbox based on dropdown selected value,
But unable to pass selected dropdown value as parameter to autocomplete url.Action()
Here is the code which I am using..
Dictionary<string, string> searchlist = new Dictionary<string, string>();
searchlist.Add("option1", "1");
searchlist.Add("option2", "2");
searchlist.Add("option3", "3");
searchlist.Add("option4", "4");
SelectList list = new SelectList(searchlist, "value", "key");
#Html.DropDownListFor(m => m.SearchType, list, new {#id="category", #class = "select" })
<script type="text/javascript">
$(document).ready(function () {
$("#category").change(function () {
var selectedVal = $("#category option:selected").text();
alert("You selected :" + selectedVal);
});
});
</script>
<input type="text" id="searchField" name="searchField" data-autocomplete-url="#Url.Action("Autocomplete", "Home", new { lang = Model.Language, cattype = selectedVal })" class="select" value="Search" onBlur="if(this.value == '') this.value = 'Search';" onFocus="if(this.value == 'Search') this.value = '';" />
<img src="#Url.Content("~/Content/images/magnifier.png")" alt="Search" title="Search" />
Please help me where am I going wrong.
Thanks in advance.
You should fire autocomplete when DDL change:
$(document).ready(function () {
$("#category").change(function () {
var selectedVal = $("#category option:selected").text();
//fire autocomlete
$('*[data-autocomplete-url]').each(function () {
$(this).autocomplete(
{
source: function (request, response) {
$.ajax({
url: $(this).attr('data-action'),
dataType: "json",
data: { lang : '#Model.Language', cattype : selectedVal },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Label,
value: item.Label,
realValue: item.Value
};
}));
},
});
},
minLength: 2,
select: function (event, ui) {
//do something
},
change: function (event, ui) {
if (!ui.item) {
this.value = '';
} else {
}
}
});
});
});
});