I have multiple kendo sliders on a page. When the value of a slider changes, I want to identify what slider triggered the change event so that I can change its color based on the value selected.
<div id="div_slider">
<input id="slider1" data-bind="kendoSlider: { value: myValue, min: 0, max: 5,change: changeSlider }" />
<input id="slider2" data-bind="kendoSlider: { value: myValue, min: 0, max: 5,change: changeSlider }" />
<input id="slider3" data-bind="kendoSlider: { value: myValue, min: 0, max: 5,change: changeSlider }" />
</div>
I have my knockout bindings as following
<script type="text/javascript">
var ViewModel = function () {
this.myValue = 5;
this.changeSlider = function(data, event) {
console.log(data);
console.log(event);
};
};
ko.applyBindings(new ViewModel());
</script>
The problem is that the event parameter of the slider change function is always undefined. Does any one have any ideas why ?
You can access the wrapping html element through the wrapper field of the widget, which is this in the handler function.
e.g.
this.changeSlider = function(){
this.wrapper.find('.k-slider-selection').css('background-color', 'red');
}
I figured it out, had to use 'this' to get the element id. Code below:
(Updated code to use the wrapper after Pechka's suggestion below)
this.changeSlider = function (data, event) {
if (data.value === 1) {
this.wrapper.find('.k-slider-selection').css('background-color', 'red');
} else if (data.value === 2) {
this.wrapper.find('.k-slider-selection').css('background-color', 'orange');
} else if (data.value === 3) {
this.wrapper.find('.k-slider-selection').css('background-color', 'yellow');
} else if (data.value === 4) {
this.wrapper.find('.k-slider-selection').css('background-color', 'green');
} else if (data.value === 5) {
this.wrapper.find('.k-slider-selection').css('background-color', 'blue');
}
};
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 have jquery UI code for confirm popup.
if (confirm('Are you sure you want to delete the batchjob:' +
dataItem["Name"])) {
$.get("#Url.Content("~/BatchJob/DeleteBatchJob")", { batchJobDetailId: parseInt(dataItem["BatchJobDetailId"]) }, function (data) {
if (data) {
debugger
var batchJobValidateWnd = $("#ValidateBatchJobStatus").data("kendoWindow");
batchJobValidateWnd.content("BatchJob deleted successfully.");
batchJobValidateWnd.center().open();
$.post("#Url.Content("~/BatchJob/SearchBatchJobDetailByParams")", { jobName: $("#Name").val(), startDate: $("#ScheduleStartDate").val() }, function (data) {
});
}
else {
debugger
window.location = '#Url.Content("~/BatchJob/Create")/' + parseInt(dataItem["BatchJobDetailId"]);
}
});
}
And I need Kendo Confirmation popup?How i change jquery confirm popup to kendo confirm popup
You can create a Kendo Confirmation Dialog via a promise, and if confirmed execute the same way as you would with a jQuery dialog.
The dialog itself should be created using an External Template which is rendered on buttonDisplayDialog click event which will wait for a response before continuing.
<script id="confirmationTemplate" type="text/x-kendo-template">
<div class="popupMessage"></div>
</br>
<hr/>
<div class="dialog_buttons">
<input type="button" class="confirm_yes k-button" value="Yes" style="width: 70px" />
<input type="button" class="confirm_no k-button" value="No" style="width: 70px" />
</div>
</script>
Based on whether the user clicks "Yes" or "No" will return result as a true or false value which is where you should put the remainder of your code:
$("#buttonDisplayDialog").kendoButton({
click: function(e) {
$.when(showConfirmationWindow('Are you sure you want to delete the batchjob:')).then(function(confirmed){
if(confirmed){
alert('This is where you will put confirmation code');
}
else{
alert('User clicked no');
}
});
}
});
});
function showConfirmationWindow(message) {
return showWindow('#confirmationTemplate', message)
};
function showWindow(template, message) {
var dfd = new jQuery.Deferred();
var result = false;
$("<div id='popupWindow'></div>")
.appendTo("body")
.kendoWindow({
width: "200px",
modal: true,
title: "",
modal: true,
visible: false,
close: function (e) {
this.destroy();
dfd.resolve(result);
}
}).data('kendoWindow').content($(template).html()).center().open();
$('.popupMessage').html(message);
$('#popupWindow .confirm_yes').val('OK');
$('#popupWindow .confirm_no').val('Cancel');
$('#popupWindow .confirm_no').click(function () {
$('#popupWindow').data('kendoWindow').close();
});
$('#popupWindow .confirm_yes').click(function () {
result = true;
$('#popupWindow').data('kendoWindow').close();
});
return dfd.promise();
};
Here is a Dojo example to demonstrate the above code in action.
Here's my form:
<form id="frmUpload" action="../scripts/upload.php" method="post" enctype="multipart/form-data">
<div id="sermonInfo">
File: <input type="file" id="uploadedFile" name="uploadedFile" class="error"><br>
<br>
Title: <input type="text" id="title" name="sermonTitle" size="35" maxlength="100">
</div>
</form>
<div id="uploadInfo">
<div class="progress">
<div class="statusBar" style="width: 0%;"></div>
<div class="percent">0%</div>
</div>
<div id="status"></div>
<br>
<div id="required">Only mp3 files are allowed!</div>
</div>
And here's the JS I'm using:
<script>
$(function() {
/*
* Upload
*/
// Reset validation and progress elements
var formValid = true,
percentVal = '0%';
$('#uploadedFile, #title').removeClass('error');
$('#status, #required').empty().removeClass();
$('.statusBar').width(percentVal)
$('.percent').html(percentVal);
$('form').ajaxForm({
beforeSend: function(e) {
if (!ValidateUploadForm()) {
formValid = false;
console.log('validateuploadform returned false');
} else {
console.log('validateuploadform returned true');
formValid = true;
}
console.log('in beforeSend. formValid: ' + formValid);
if (!formValid) {
return false;
}
},
uploadProgress: function(event, position, total, percentComplete) {
console.log('in uploadProgress function. formValid: ' + formValid);
if (formValid) {
var percentVal = percentComplete + '%';
$('.statusBar').width(percentVal)
$('.percent').html(percentVal);
}
},
complete: function(xhr) {
console.log('in complete function. formValid: ' + formValid);
if (formValid) {
console.log('xhr.responseText: ' + xhr.responseText);
console.log('formValid: ' + formValid);
if (xhr.responseText === 'success') {
$('.statusBar').width('100%');
$('.percent').html('100%');
$('#status').html('Successfully uploaded the file.').addClass('successUpload');
// Clear the form
ClearForm();
} else if (xhr.responseText === 'fail') {
$('#status').html('There was a problem uploading the file. Try again.<br>If the problem persists, contact your system administrator.').addClass('errorUpload');
}
}
}
}); // End Upload Status Bar
});
function ValidateUploadForm() {
// Reset errors and clear message
$('#uploadedFile, #title').removeClass('error');
$('#required').empty();
var result = true;
title = $('#title').val(),
fileName = $('#uploadedFile').val();
extension = $('#uploadedFile').val().split('.').pop();
if (fileName !== '' && extension !== 'mp3') {
$('#uploadedFile').addClass('error');
$('#required').html('Only mp3 files are allowed!');
return false;
} else if (fileName === '') {
result = false;
} else if (title === '') {
$('#title').addClass('error');
result = false;
}
console.log('returning ' + result + ' from the validateuploadform function');
if (!result) { $('#required').html('All fields are required.'); }
return result;
}
function ClearForm() {
$('#uploadedFile, #title').val('').removeClass();
}
</script>
As you can see, I'm using console output the keep an eye on what's going on.
My problem is, if a file is selected, the file still uploads, whether formValid (in beforeSend) is true or false.
I've tried adding preventDefault before return false;. I've also tried clearing the file input in the if (!formValid) {} block. As you can see, I've wrapped the uploadProgress and complete functions to check if formValid is false. If the console output in uploadProgress shows formValid to be false, the file still uploads.
What am I missing here? How can I prevent the file upload if the validation fails?
I finally figured out the issue: I was comparing my script to some examples online and noticed that the examples' callback was named beforeSubmit, but I was using beforeSend.
Oddly, the validation code was still executing, but returning false didn't stop the upload.
Basically, it looks like you might be missing the jquery.form.js extension. Without JavaScript console output, I can only guess that that ought to be the problem. Try the following (entire) page as a reference, where stopping the upload works:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Test Page</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" type="text/javascript">
</script>
<script src="http://malsup.github.com/jquery.form.js" type="text/javascript">
</script>
<style type="text/css">
div.c1 {width: 0%;}
</style>
</head>
<body>
<form id="frmUpload" action="%3C?php%20basename(__FILE__,%20'.php');%20?%3E" method="post" enctype="multipart/form-data" name="frmUpload">
<div id="sermonInfo">File: <input type="file" id="uploadedFile" name="uploadedFile" class="error"><br>
<br>
Title: <input type="text" id="title" name="sermonTitle" size="35" maxlength="100"></div>
<input type="submit" value="Submit"></form>
<div id="uploadInfo">
<div class="progress">
<div class="statusBar c1"></div>
<div class="percent">0%</div>
</div>
<div id="status"></div>
<br>
<div id="required">Only mp3 files are allowed!</div>
</div>
<script type="text/javascript">
$(function() {
/*
* Upload
*/
// Reset validation and progress elements
var formValid = true,
percentVal = '0%';
$('#uploadedFile, #title').removeClass('error');
$('#status, #required').empty().removeClass();
$('.statusBar').width(percentVal)
$('.percent').html(percentVal);
$('form').ajaxForm({
beforeSend: function(e) {
if (!ValidateUploadForm()) {
formValid = false;
console.log('validateuploadform returned false');
} else {
console.log('validateuploadform returned true');
formValid = true;
}
console.log('in beforeSend. formValid: ' + formValid);
if (!formValid) {
return false;
}
},
uploadProgress: function(event, position, total, percentComplete) {
console.log('in uploadProgress function. formValid: ' + formValid);
if (formValid) {
var percentVal = percentComplete + '%';
$('.statusBar').width(percentVal)
$('.percent').html(percentVal);
}
},
complete: function(xhr) {
console.log('in complete function. formValid: ' + formValid);
if (formValid) {
console.log('xhr.responseText: ' + xhr.responseText);
console.log('formValid: ' + formValid);
if (xhr.responseText === 'success') {
$('.statusBar').width('100%');
$('.percent').html('100%');
$('#status').html('Successfully uploaded the file.').addClass('successUpload');
// Clear the form
ClearForm();
} else if (xhr.responseText === 'fail') {
$('#status').html('There was a problem uploading the file. Try again.<br>If the problem persists, contact your system administrator.').addClass('errorUpload');
}
}
}
}); // End Upload Status Bar
});
function ValidateUploadForm() {
// Reset errors and clear message
$('#uploadedFile, #title').removeClass('error');
$('#required').empty();
var result = true;
title = $('#title').val(),
fileName = $('#uploadedFile').val();
extension = $('#uploadedFile').val().split('.').pop();
if (fileName !== '' && extension !== 'mp3') {
$('#uploadedFile').addClass('error');
$('#required').html('Only mp3 files are allowed!');
return false;
} else if (fileName === '') {
result = false;
} else if (title === '') {
$('#title').addClass('error');
result = false;
}
console.log('returning ' + result + ' from the validateuploadform function');
if (!result) { $('#required').html('All fields are required.'); }
return result;
}
function ClearForm() {
$('#uploadedFile, #title').val('').removeClass();
}
</script>
</body>
</html>
As a side note, you might want to use
extension = $('#uploadedFile').val().split('.').pop().toLowerCase();
to make sure that the form also accepts MP3, as this is seen relatively often too in the wild.
If this doesn't fix your problem, it would help if you could upload the full HTML of one page in question.
UPDATE
With respect to the uploaded files, you have a simple typo in line 91 of testUpload.php:
if ((fileName === '') || (extension !== 'mp3'))
should be
if ((fileName === '') || (extension !== 'mp3')) {
I am trying to get autocomplete working on any div with the id="train" however, it seems to only be working on the first input field with a class of "train"
javascript code:
<script type="text/javascript">
$(document).ready(function() {
$(".train").each(function() {
$(".train").keyup(function() {
$("#suggest_q").html("");
var train = $(".train").val();
train = $.trim(train);
if(train)
{
$.ajax({
url: "train_ajax_query.php",
data: "train="+train,
success: function(msg) {
$("#suggest_q").html(msg);
$("#suggest_q ul li").mouseover(function() {
$("#suggest_q ul li").removeClass("hover");
$(this).addClass("hover");
})
$("#suggest_q ul li").click(function() {
var value = $(this).html();
$("#train").val(value);
$("#suggest_q ul li").remove();
});
}
});
}
});
});
});
</script>
HTML code:
<form id="train_create_form" name="train" action="submit_train.php" method="POST">
<input type="text" id="train" class="train" size="20" name="train[]" placeholder="Train 1" />
<div id="suggest_q">
</div>
<input type="text" id="train" size="20" class="train" name="train[]" placeholder="Train 2" />
<div id="suggest_q">
</div>
<input id= "submit_train" type="submit" name="submit_train" value="Submit All trains">
</form>
I found this old post but I am not sure how to adopt the fix for my problem :(
add more input fields code:
<script type="text/javascript">
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 0;
$('#addScnt').live('click', function() {
$('<p><input type="text" id="train" name="train[]" class="train" placeholder="Train ' + i +'" /><div id="suggest_q"></div>Remove train</p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
Beause here:
$(".train").each(function() {
$(".train").keyup(function() {
you get every time only first field :) try:
$(".train").each(function(index, element) {
element.keyup(function() {
// or even: $(element).keyup(function() {
References:
Each
KeyUp
Val
I copypaste whole example:
<script type="text/javascript">
$(document).ready(function() {
$(".train").each(function(index, element) {
$(element).keyup(function() {
$("#suggest_q").html("");
var train = $(element).val();
train = $.trim(train);
if(train)
{
$.ajax({
url: "train_ajax_query.php",
data: "train="+train,
success: function(msg) {
$("#suggest_q").html(msg);
$("#suggest_q ul li").mouseover(function() {
$("#suggest_q ul li").removeClass("hover");
$(this).addClass("hover");
})
$("#suggest_q ul li").click(function() {
var value = $(this).html();
$(element).val(value);
$("#suggest_q ul li").remove();
});
}
});
}
});
});
});
Each time you type $(".train"), you're searching again for all the elements.
Once you've done your initial $(".train").each(function() { line, you can just use $(this) to refer to the element, and that function will get called on each element.
When you use var train = $(".train").val(); you are getting just the value of the first element. See http://api.jquery.com/val/ for more details on why.
If you remove that line and just use $(this) instead of '''train''' this should work better, but you will also want to get rid of the .each() around the .keyup(), since $(".train").keyup will already apply to all matching elements.
You're basically saying "go through and find all train elements. For each one, go through and set the keyup value on all train elements. Set it to a function which enforces autocomplete on the first train element". You want to be saying "Set the keyup callback on each train elements to enforce autocomplete on itself"
I use this tooltip plugin to make the tooltip on element as
$('.showtooltip').tooltip({
delay: 0,
track: true,
showURL: false,
bodyHandler: function() {
var tipStr = "SOME DISPLAY HTML";
return $(tipStr);
}
});
And my ajax create element dynamically.
$("<img alt='' class='showtooltip' src='image.jpg' />");
so when this image is added to document. The tooltip doesn't display.
Then I use live() in jquery :
$(".showtooltip").live("mouseover", function() {
$(this).tooltip({
delay: 0,
track: true,
showURL: false,
bodyHandler: function() {
var tipStr = "SOME DISPLAY HTML";
return $(tipStr);
}
})
});
But tooltip only display after the first time mouse over the image.
How can i use tooltip on dynamic element ?
I used something like this to rebind after an ajax call. It may help.
$(".showtooltip").live("mouseover",function(){
if (!$(this).hasClass("tooledUp")){
$(this).tooltip({
delay: 0,
track: true,
showURL: false,
bodyHandler: function() {
var tipStr = "SOME DISPLAY HTML";
return $(tipStr);
}
});
$(this).tooltip().show();
$(this).addClass("tooledUp");
}
});
From the forum here: http://static.flowplayer.org/tools/forum/30/37281
<input type="button" id="btn" value ="Click here" />
$(document).ready(function(){
$("#btn").click(function(){
$("<input type='checkbox' title='waaaaw' />").appendTo($(this).parent()).ready(function(){
$(this).tooltip({
delay: 0,
track: true,
showURL: false,
bodyHandler: function() {
var tipStr = "SOME DISPLAY HTML";
return $(tipStr);
}
}).addClass("tooledUp").show();
});
});
});