I want to clone a html control and then append to another control.
I have written code
ko.bindingHandlers.multiFileUpload = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = ko.utils.unwrapObservable(valueAccessor()),
controlId = ko.utils.unwrapObservable(options.controlId);
//primaryKey = ko.utils.unwrapObservable(options.primaryKey);
var progressMonitorID = controlId + '-ProgressMonitor';
var progressIndicatorID = controlId + '-ProgressIndicator';
$(element).after('<div id=' + progressMonitorID + ' class="progress progress-striped active">'
+ '<div id=' + progressIndicatorID + ' class="bar" style="width: 0%;"></div>'
//+ '<input type="hidden" id="imageKey_"' + controlId + ' name="imageKey" value=' + primaryKey + '></div>'
+ '</div>');
$('#' + progressMonitorID).hide();
$('#' + progressIndicatorID).hide();
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = ko.utils.unwrapObservable(valueAccessor()),
imageKey = ko.utils.unwrapObservable(options.imageKey),
imageForeighKey01 = ko.utils.unwrapObservable(options.imageForeighKey01),
uploadUrl = ko.utils.unwrapObservable(options.uploadUrl),
controlId = ko.utils.unwrapObservable(options.controlId),
refreshUri = ko.utils.unwrapObservable(options.refresh),
formName = ko.utils.unwrapObservable(options.formName);
var progressMonitorID = controlId + '-ProgressMonitor';
var progressIndicatorID = controlId + '-ProgressIndicator';
var formID = controlId + '-form';
var fileInputID = controlId + '-fileInput';
if (uploadUrl) {
$(element).change(function () {
if (element.files.length) {
var $this = $(this),
fileName = $this.val();
// var formData = new FormData($('#' + formName)[0]);
var $form = $('<form enctype="multipart/form-data" id=' + formID + '></form>');
// $form.append('<input id=' + fileInputID + 'name=' + fileInputID + ' type="file" />');
$form.append('<input type="hidden" id="imageKey_"' + controlId + ' name="imageKey" value=' + imageKey + '>');
$form.append('<input type="hidden" id="imageForeignKey_"' + controlId + ' name="imageForeighKey01" value=' + imageForeighKey01 + '>');
$("#" + controlId).clone().appendTo($form);
$form.hide();
$('body').append($form);
var formData = new FormData($($form)[0]);
$.ajax({
url: uploadUrl,
type: 'POST',
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false, //'multipart/form-data',
processData: false,
xhr: function () {
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total * 100 + "%";
//Do something with upload progress
$('#' + progressMonitorID).show();
$('#' + progressIndicatorID).width(percentComplete);
//alert(percentComplete);
}
}, false);
return xhr;
}
})
.done(function (data, textStatus, jqXHR) {
if (refreshUri) {
//alert("success");
//var path = '../MapView/DownloadMap?ref=' + Math.random();
var path = refreshUri + 'ref=' + Math.random();
options.refresh(path);
}
})
.fail(function (jqxhr, status, errorMsg) { alert("Status : " + status + " Error :" + errorMsg); })
.always(function () {
// alert("complete");
$('#' + progressMonitorID).hide();
$('#' + progressIndicatorID).hide();
$('#' + formID).remove();
});
}
});
}
}
}
and html binding is
<input type="file" tabindex="9"
data-bind="attr: {
id: 'RoadMap' + $index(), name: 'RoadMap' + $index()
},
multiFileUpload: {
controlId: 'RoadMap' + $index(),
formName: 'frmPage3a',
imageKey: StageDetailID,
imageForeighKey01: CourseInfoRoadID,
uploadUrl: '/api/Image/UploadMapFile'
}
" />
this code works very fine into FireFox browser but not work in IE and Chrome.here the problem is .clone() method of jquery.
Is it possible? Thanks.
You are assigning id with an underscore and this is why not working. Use two backslashes to escape meta character. Like $("#your\\_id")
see more info here
Related
I have this jqgrid code below and I have a picture inside it and at the same time its function that I am using. But clicking the button inside my jqgrid it says Uncaught ReferenceError: clickmeapproved is not defined. Is there anything wrong with my code or the way that I am using them?. Same error with the disapproved button.
afterInsertRow: function (rowid) {
var obj = jQuery("#FiTATimeCorrectionV2List").getRowData(rowid);
var FADTLSID = obj.FitaAssignDtlID;
if (FADTLSID !== undefined) {
if (FADTLSID !== "") {
var btnApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/check.png' style='height:20px;width:20px;' style ='width: 90px' id='btnApproved" + rowid + "' onclick='clickmeapproved(" + rowid + " )' />"
var btnDisApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/delete.png' style='height:20px;width:20px;' style ='width: 90px' id='btnDisApproved" + rowid + "' onclick='clickmedisapproved(" + rowid + " )' />"
jQuery("#FiTATimeCorrectionV2List").setRowData(rowid, { FitaCorForApproval: btnApprove });
jQuery("#FiTATimeCorrectionV2List").setRowData(rowid, { FitaCorForDisApproval: btnDisApprove });
var temp = obj.FitaStatus;
if (temp == "Approved") {
$("#btnApproved" + rowid).hide();
$("#btnDisApproved" + rowid).hide();
}
else if (temp == "Disapproved") {
$("#btnApproved" + rowid).hide();
$("#btnDisApproved" + rowid).hide();
} else {
$("#btnApproved" + rowid).show();
$("#btnDisApproved" + rowid).show();
}
}
}
},
function clickmeapproved(rowid) {
var ans = confirm("Are you sure you want to approve the request of "+ globalFitaCorName +"?");
if (ans) {
$.ajax({
type: "POST",
url: '../Request/SaveFitaApproval?FAID=' + rowid,
dataType: 'json',
success: function (response) {
alert("Successfully approve!");
$("#FiTATimeCorrectionV2List").trigger("reloadGrid");
FiTATimeCorrectionV2(0);
globalFitaCorName = "";
$("#loader").hide();
},
error: function (reponse) {
$("#FiTATimeCorrectionV2List").trigger("reloadGrid");
FiTATimeCorrectionV2(0);
globalFitaCorName = "";
$("#loader").hide();
}
});
}
}
Your "clickmeapproved" function does not have global scope. Check by typing "window.clickmeapproved" in the web inspector.
Here is the code that I use to solve my issue.
var btnApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/check.png' style='height:20px;width:20px;' style ='width: 90px' id='btnApproved" + rowid + "' />"
var btnDisApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/delete.png' style='height:20px;width:20px;' style ='width: 90px' id='btnDisApproved" + rowid + "' />"
I exclude the button click from it.
$("#btnApproved" + rowid + "").click(function(){
clickmeapproved(rowid);
});
$("#btnDisApproved" + rowid + "").click(function(){
clickmedisapproved(rowid);
});
I added a delete function to a todo list app that i built. The delete function works; however, when I refresh the page all the items that i deleted come back. How can I remove the items permanently from the database?
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
//////this section works
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
///////this does not want to remove the item from the database
$.destroy("/tasks/" + itemId, {
_method: "destroy",
task: {
done: doneValue
}
});
});
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
// still dont understand this
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
var li_to_delete = $('.todo-list li.completed');
$.ajax({
type: 'DELETE',
url: "/tasks" + li_to_delete,
success: function(){
li_to_delete.remove();
}
});
});
});
i changed the code but im not sure how to properly extract the url.
I've been working on this for like an hour now, but can't seem to figure it out.
The JSON response:
{"lastDate":"2013-11-22 00:00:35",
"lastId":"42460",
"response":[
{
"class":"rowgreen",
"id":"42460","date":"22 November 2013, 00:00:35\\u0026nbsp;",
"player":"\\u003Ca href=\\u0027logpersonal.php?playerName=skiwi2\\u0027\\u003Eskiwi2\\u003C\/a\\u003E\\u0026nbsp;",
"target":"\\u003Ca href=\\u0027logpersonal.php?playerName=UnholiestElite\\u0027\\u003EUnholiestElite\\u003C\/a\\u003E\\u0026nbsp;",
"weapon":"M1014 (\\u003Cb\\u003EHeadshot\\u003C\/b\\u003E)\\u0026nbsp;",
"server":"Test\\u0026nbsp;"
}
]}
This seems to be correct, now the jquery:
function longPolling() {
if (!longPollingAllowed) {
return;
}
console.log("Long polling started.");
$.ajax({
url: "logpersonal_ajax.php",
data: {
serverId: serverId,
playerName: playerName,
lastDate: lastDate,
lastId: lastId
},
cache: false,
dataType: "json",
beforeSend: function() {
longPollingBusy = true;
},
success: function(json) {
console.log("success");
$(json).each(function() {
console.log("this.lastDate = " + this.lastDate);
console.log("this.lastId = " + this.lastId)
console.log("this.response = " + this.response);
console.log(this.response);
this.lastDate = this.lastDate;
this.lastId = this.lastId;
if (this.response != "") {
this.response.each(new function() {
console.log(this);
var clazz = this.class;
console.log("clazz = " + clazz);
var id = this.id;
var date = this.date;
var player = this.player;
var target = this.target;
var weapon = this.weapon;
var server = this.server;
var string = "\t\t\t<tr class='" + clazz + "' id='" + id + "'><td>" + date + "</td><td>" + player + "</td><td>" + target + "</td><td>" + weapon + "</td><td>" + server + "</td></tr>\n";
console.log("string = " + string);
$(string).insertBefore($("#list tr.header").next());
});
}
});
if (lastDate != "" && lastId != "") {
//longPolling(serverId, playerName, lastDate);
}
longPollingBusy = false;
},
error: function(json, message) {
console.log("fail: " + message);
longPollingBusy = false;
}
});
}
The console.log("this.lastDate = " + this.lastDate); works, so does the one for this.lastId. this.response also works and nicely shows an array starting with index 0 and when expanded it you can see all elements in the developer view.
Now comes the part I cannot seem to understand: At the foreach over this.response it does not print anything useful (except Prototype skeleton) for this.
How can I access the values?
this.response.each(new function() {
This line is wrong. It should be:
this.response.forEach(function() {
P.S. I suggest doing $.each(json, function(){ instead of $(json).each(function() {.
I am trying to make a dynamic form wherein a single item has a file, text and select html input types and number of items can be dynamic. The problem is when doing AJAX using jquery, the Form wont serialize for the file input type. Please suggest any technique to do it. My code is below:
<form id="Form1" enctype="multipart/form-data">
<div id="divMain"></div>
<div>
<button id="Upload" type="button" value="Upload"><span>Upload</span></button>
<input id="Add" type="button" value="Add" />
</div>
</form>
<div id="status"></div>
<script type="text/javascript">
var counter = 0;
AddElements(); //add first element
$("#Add").click(function () {
AddElements();
});
function AddElements() {
counter++;
$("#divMain").append("<div><input id='Browse" + counter + "' name='Browse[]' type='file' value='Browse' data-target='#Name" + counter + "' />" +
"<input id='Name" + counter + "' name='Name[]' type='text'/>" +
"<select id='Type" + counter + "' name='Type[]'>" +
"<option>Option1</option>" +
"<option>Option2</option>" +
"</select></div>");
$("#Browse" + counter + "").change(function () {
var filename = $(this).val();
var textbox = $($(this).attr("data-target"));
var lastIndex = filename.lastIndexOf("\\");
var b = filename.lastIndexOf(".");
if ((b == -1) | (b < lastIndex))
filename = filename.substring(lastIndex + 1);
else
filename = filename.substring(lastIndex + 1, b - lastIndex - 1);
textbox.val(filename);
});
}
$("#Upload").click(function (e) {
e.preventDefault();
$("#status").html('Uploading....');
var ajaxData = $("#Form1").serialize();
$.ajax({
url: "AjaxPostDemo.aspx",
type: "POST",
data: ajaxData,
cache: false,
processData: false,
success: function (data) {
$("#status").html("success: " + data);
},
error: function (result) {
$("#status").html("error: " + result);
}
});
});
</script>
Change Your To script It Will Definately Work. :-)
<script type="text/javascript">
var counter = 0;
$(document).ready(function () {
AddElements(); //add first element
$("#Add").click(function () {
AddElements();
});
function AddElements() {
counter++;
$("#divMain").append("<div><input id='Browse" + counter + "' name='Browse[]' type='file' value='Browse' data-target='#Name" + counter + "' />" +
"<input id='Name" + counter + "' name='Name[]' type='text'/>" +
"<select id='Type" + counter + "' name='Type[]'>" +
"<option>Option1</option>" +
"<option>Option2</option>" +
"</select></div>");
$("#Browse" + counter + "").change(function () {
var filename = $(this).val();
var textbox = $($(this).attr("data-target"));
var lastIndex = filename.lastIndexOf("\\");
var b = filename.lastIndexOf(".");
if ((b == -1) | (b < lastIndex))
filename = filename.substring(lastIndex + 1);
else
filename = filename.substring(lastIndex + 1, b - lastIndex - 1);
textbox.val(filename);
});
}
});
$(document).ready(function () {
$("#Upload").click(function (e) {
e.preventDefault();
$("#status").html('Uploading....');
var ajaxData = $("#Form1").serialize();
$.ajax({
url: "AjaxPostDemo.aspx",
type: "POST",
data: ajaxData,
cache: false,
processData: false,
success: function (data) {
$("#status").html("success: " + data);
},
error: function (result) {
$("#status").html("error: " + result);
}
});
});
});
</script>
Second Option
http://www.uploadify.com/documentation/uploadify/multi/
Prefer This It will Uploaded Multifiles on one time with great UI. :-)
i'm using this template for a personal project.
https://github.com/blueimp/Bootstrap-Image-Gallery
and there is this code here that gets photos from flickr. This code uses the method flickr.interestingness.getList which takes tags as an argument as seen here. http://www.flickr.com/services/api/flickr.interestingness.getList.html
I want to pass in tags as an argument, but I can't figure out the syntax for doing so in ajax or w/e the format being used in this code is.
// Load images via flickr for demonstration purposes:
$.ajax({
url: 'http://api.flickr.com/services/rest/',
data: {
format: 'json',
method: 'flickr.interestingness.getList',
api_key: 'API_KEY_abc123'
},
dataType: 'jsonp',
jsonp: 'jsoncallback'
}).done(function (data) {
var gallery = $('#gallery'),
url;
$.each(data.photos.photo, function (index, photo) {
url = 'http://farm' + photo.farm + '.static.flickr.com/' +
photo.server + '/' + photo.id + '_' + photo.secret;
$('<a data-gallery="gallery"/>')
.append($('<img>').prop('src', url + '_s.jpg'))
.prop('href', url + '_b.jpg')
.prop('title', photo.title)
.appendTo(gallery);
});
This seems like a better project:
http://petejank.github.io/js-flickr-gallery/
/*
* Bootstrap Image Gallery JS Demo 3.0.0
* https://github.com/blueimp/Bootstrap-Image-Gallery
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
* Plugin was modified by ravindu
*/
(function( $ ) {
$.fn.flickr = function(options) {
var url = 'http://api.flickr.com/services/rest/?jsoncallback=?';
var settings = $.extend( {
'api_key': 'YOUR API',
}, options);
function view_image(event) {
var target = $(event.target);
if(target.is('img')) {
var url = target.attr('data-url');
var cache = new Image();
cache.src = url;
var gallery = target.parents('.flickr-gallery:first').children('div.viewport');
var info = gallery.children('div.image-info');
var image = gallery.children('img');
image.fadeOut('slow', function () {
image.attr('src', url);
image.fadeIn('slow');
info.html(target.attr('data-title') + '<br />' + target.attr('data-tags'));
});
}
}
return this.each(function() {
var gallery = $(this);
gallery.addClass('flickr-gallery');
gallery.append('<h2></h2><h3></h3><div class="viewport"></div><div class="browser"><ul></ul></div><div class="clear"></div>');
$.getJSON(url, {
method: 'flickr.photosets.getInfo',
api_key: settings.api_key,
photoset_id: settings.photoset_id,
format: 'json'
}).success(function(state) {
gallery.children('h3').html(state.photoset.description._content);
gallery.find('.loader').addClass('activate');
$.getJSON(url, {
method: 'flickr.photosets.getPhotos',
api_key: settings.api_key,
media: 'photos',
photoset_id: settings.photoset_id,
format: 'json',
extras: 'url_sq,url_m,url_b,date_taken,tags'
}).success(function(state) {
$('.loader').removeClass('activate');
var list = gallery.find('ul:first');
list.html('');
list.on('click', view_image);
$.each(state.photoset.photo, function(index, photo){
baseUrl = 'http://farm' + photo.farm + '.static.flickr.com/' +
photo.server + '/' + photo.id + '_' + photo.secret;
list.append('<a href="' + this.url_m + '" title="' + this.title + '" data-gallery="" > <img src="' + this.url_sq + '" title="' + this.title + '" ' +
'data-title="' + this.title + '" ' +
'data-url="' + this.url_m + '" ' +
( this.date_taken ? 'data-date="' + this.date_taken + '" ' : '' ) +
'data-tags="' + this.tags + '" ' +
'/></a>');
});
}).fail(function(state) {
alert("Unable to retrieve photo set");
});
}).fail(function(state) {
alert("Unable to retrieve photo set information");
});
});
};
})( jQuery );
$(document).on('ready', function(){
$('#photos-1').flickr({ photoset_id:'72157640241840746'});
$('#photos-2').flickr({ photoset_id:'72157640251299195'});
$('#photos-3').flickr({ photoset_id:'72157640241840746'});
$('#photos-4').flickr({ photoset_id:'72157640251299195'});
$('#photos-5').flickr({ photoset_id:'72157640241840746'});
});