t I have been trying to resolve this issue for two days, and I'm getting crazy, plea a little help.
I'm trying to append a new div (insert html code), within an anchor, it seems ok, but the link does not work. I'm trying to use a class='delete', to call another jquery function to deleted the new div element. The idea is a shopping cart, I add a producto, and after added, I want to delete, but it's not working. Here is my code:
$("#dialog-form").dialog({
autoOpen: false,
height: 320,
width: 320,
modal: true,
show: 'slide',
buttons: {
"Agregar Tour": function () {
var bValid = true;
allFields.removeClass("ui-state-error");
bValid = bValid && checkLength(adl, "Adultos", 1, 5);
bValid = bValid && checkLength(chls, "NiƱos", 0, 5);
bValid = bValid && checkLength(fecha, "Fecha", 1, 16);
var id = $(this).val("id");
var string = 'tourid=' + tourid;
//var tourid = '<?php echo $moneda ?>';
//alert(tourid);
if (bValid) {
$.ajax({
url: "add_item.php",
data: "tourid=" + tourid + "&adl=" + adl.val() + "&chl=" + chls.val() + "&fecha=" + fecha + "",
dataType: 'json',
type: "GET",
cache: false,
success: function (data) {
var regis = data[0];
var titulo = data[6];
var desc = data[7];
var total = data[12];
var foto = data[15];
var items = data[21];
var ruta = "images/hoteles/" + foto + "";
$("#containerx").append("<div id='containerx' class='koko' ><b><font color='#3399CC'>" + titulo + "</font></b><br>" + desc + "<br>" + "<b><font color='#ff0099'>Sub-total </font></b><image src='images/arrow.gif'> $" + total + " MXP " + "<a href='#' id=" + regis + " class='delele'>" + "<image src='images/delete.gif'></a></div><div style='clear:both;'></div>");
$("#containerx.koko").fadeTo(1000, 0.7);
$("#dialog-message").dialog({
modal: true,
show: 'slide',
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});
$("#items").html("<div id='items'>[" + items + "]</div>");
$('#load').fadeOut();
}
});
$(this).dialog("close");
}
},
Cancel: function () {
$(this).dialog("close");
}
},
close: function () {
allFields.val("").removeClass("ui-state-error");
}
});
$(".add-item").button().click(function () {
tourid = $(this).attr("id");
$("#dialog-form").dialog("open");
});
On this "delete" event etc you need to use "live" jquery live http://api.jquery.com/live/ or attach the events again after you add content.
Simply once content is rendered all events are attached, if you are dynamically adding new content you need to attach events again if they are not "live" events.
jquery "Live" event will try to attach to dynamically added content also :). Read the doc i added and you will know all.
Related
I'm using the dragable and droppable function in javascript to move cells in a GridView.
Everything works, the only thing I don't like, when I move a cell it shifts everything as if moving the td.
The programming language used is VB.NET, while the drag-and-drop part I used Javascript.
Do you think it is also possible to insert the switch function between two names in two different cells?
Any advice?
Thank you very much!!
Gif of what's going on
var colIndex, rowIndex;
$('[id^="GridView"] tr td').draggable({
revert: "invalid",
zIndex: 100,
start: function (event, ui) {
var foo = $(ui.helper).parent();
colIndex = foo.index();
rowIndex = foo.parent().index();
$(ui.helper).css({
padding: "2.5px 5px",
border: "1px solid #ddd",
background: "#f2f2f2"
});
}
});
$('#GridView2 tr td').droppable({
accept: "#GridView1 tr td, #GridView2 tr td",
activeClass: "ui-state-highlight",
drop: function (ev, ui) {
var foo2 = $(ui.helper).parent();
colIndex2 = foo2.index();
rowIndex2 = foo2.parent().index();
var foo = $(ev.target);
var spanCount = foo.find('span').length;
var myColInd = foo.index();
var myRowInd = foo.parent().index();
var text_dest = foo.text();
if (text_dest == String.fromCharCode(160) || text_dest == '') {
var x = document.getElementById($(this).closest('table').attr('id')).rows
var y = x[myRowInd].cells
y[myColInd].innerHTML = ""
$(ui.draggable).detach().css({
top: 'auto',
left: 'auto',
background: '#f3f3f3'
}).appendTo(this);
var arr = [];
$("#" + $(this).closest('table').attr('id') + " tr").each(function () {
arr.push($(this).find("th").eq(myColInd).text());
});
var arr2 = [];
$("#" + $(this).closest('table').attr('id') + " tr").each(function () {
arr2.push($(this).find("td").eq(myColInd).text());
});
let prefix = $('#DropDownList1').val() + ',Lu,' + myRowInd + ',' + arr[0] + ',' + arr2[myRowInd] + ',' + $('#Label1').text() + ',' + $('#Label2').text();
$.ajax({
type: "POST",
url: "index.aspx/InsRec",
data: "{ 'prefix': '" + prefix + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: code1
});
}
else {
$(ui.draggable).draggable('option', 'revert', true);
return false;
};
}
});
Im working in a chat system very simple. But i have a problem. I can only get the other user messages if i close and re open the chat conversation div, then the message appears.
How can I solve this? The problem should be in this piece of code. As I am not very comfortable with ajax I ask for your help.
JS:
$(document).ready(function(){
var snd = new Audio("images/new_msg.wav");
var open=Array();
$("#jd-chat .jd-online_user").click(function(){
var user_name = $.trim($(this).text());
var id = $.trim($(this).attr("id"));
if($.inArray(id,open) !== -1 )
return
open.push(id);
$("#jd-chat").prepend('<div class="jd-user">\
<div class="jd-header" id="' + id + '">' + user_name + '<span class="close-this"> X </span></div>\
<div class="jd-body"></div>\
<div class="jd-footer"><input id="textareabox" placeholder="escrever..."></div>\
</div>');
$.ajax({
url:'chat.class.php',
type:'POST',
data:'get_all_msg=true&user=' + id ,
success:function(data){
$("#jd-chat").find(".jd-user:first .jd-body").append("<span style='display:block' class='me'> " + data + "</span>");
}
});
});
$("#jd-chat").delegate(".close-this","click",function(){
removeItem = $(this).parents(".jd-header").attr("id");
$(this).parents(".jd-user").remove();
open = $.grep(open, function(value) {
return value != removeItem;
});
});
$("#jd-chat").delegate(".jd-header","click",function(){
var box=$(this).parents(".jd-user,.jd-online");
$(box).find(".jd-body,.jd-footer").slideToggle();
});
$("#search_chat").keyup(function(){
var val = $.trim($(this).val());
$(".jd-online .jd-body").find("span").each(function(){
if ($(this).text().search(new RegExp(val, "i")) < 0 )
{
$(this).fadeOut();
}
else
{
$(this).show();
}
});
});
$("#jd-chat").delegate(".jd-user input","keyup",function(e){
if(e.keyCode == 13 )
{
var $cont = $('.jd-body');
var box=$(this).parents(".jd-user");
var msg=$(box).find("input").val();
var to = $.trim($(box).find(".jd-header").attr("id"));
$.ajax({
url:'chat.class.php',
type:'POST',
data:'send=true&to=' + to + '&msg=' + msg,
success:function(data){
$('#textareabox').val('');
$(box).find(".jd-body").append("<span style='display:block' class='me'> " + msg + "</span>");
$cont[0].scrollTop = $cont[0].scrollHeight;
$cont.append('<span>' + $(this).val() + '</span>');
$cont[0].scrollTop = $cont[0].scrollHeight;
$(this).val('');
}
});
}
});
function message_cycle()
{
$.ajax({
url:'chat.class.php',
type:'POST',
data:'unread=true',
dataType:'JSON',
success:function(data){
$.each(data , function( index, obj ) {
var user = index;
var box = $("#jd-chat").find("div#2").parents(".jd-user");
$(".jd-online").find(".light").hide();
$.each(obj, function( key, value ) {
if($.inArray(user,open) !== -1 )
$(box).find(".jd-body").append("<span style='display:block' class='other'> " + value + "</span>");
else
snd.play();
$(".jd-online").find("span#" + user + " .light").show();
});
});
}
});
}
setInterval(message_cycle,1000);
});
How messages are displayed when you first open the chat conv div ?
I'm assuming message_cycle() is supposed to display new messages in your div every second, i suppose your problem is here...
I'm not really confortable with this :
var box = $("#jd-chat").find("div#2").parents(".jd-user");
A div can't have an id starting with a number, you need <div id="chat2"> instead of <div id="2">.
After your line add a console.log('Box found : '+box.length) ; just to make sure your box is correctly found in message_cycle.
I'm using blueimp/jQuery-File-Upload's plugin to upload files and I'm trying (unsuccessfully) to add a data-attribute to the preview when the upload is done.
Here is the code:
$('#fileupload').fileupload({
autoUpload: true,
disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png|bmp|doc?x|pdf|xml|psd|tif)$/i,
uploadTemplateId: null,
downloadTemplateId: null,
uploadTemplate: function (o) {
var rows = $();
$.each(o.files, function (index, file) {
var row = $('<div class="template-upload fade">' +
'<span class="preview"></span>' +
'<p class="name"></p>' +
'<div class="error"></div>' +
'<div class="progress"></div>' +
(!index && !o.options.autoUpload ?
'<button class="start" disabled>Start</button>' : '') +
(!index ? '<button class="cancel">Cancel</button>' : '') +
'</td>' +
'</div>');
row.find('.name').text(file.name);
row.find('.size').text(o.formatFileSize(file.size));
if (file.error) {
row.find('.error').text(file.error);
}
rows = rows.add(row);
});
return rows;
},
downloadTemplate: function (o) {
var rows = $();
$.each(o.files, function (index, file) {
var row = $('<div class="template-download fade">' +
'<span class="preview"></span>' +
'<p class="name"></p>' +
(file.error ? '<div class="error"></div>' : '') +
//'<button class="delete">Delete</button>' +
'</div>');
row.find('.size').text(o.formatFileSize(file.size));
if (file.error) {
row.find('.name').text(file.name);
row.find('.error').text(file.error);
} else {
row.find('.name').append($('<a></a>').text(file.name));
if (file.thumbnailUrl) {
row.find('.preview').append(
$('<a></a>').append(
$('<img>').prop('src', file.thumbnailUrl)
)
);
}
row.find('a')
.attr('data-gallery', '')
.prop('href', file.url);
row.find('button.delete')
.attr('data-type', file.delete_type)
.attr('data-url', file.delete_url);
}
rows = rows.add(row);
});
return rows;
}
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
}).bind('fileuploaddone', function(e, data) {
var arquivo = data.result.files[0].url;
var varCodTipoProcesso = $('.indexador-campo').data('cod-tipo-processo');
var varCodEstabelecimento = $('.estabelecimento-select').parent().children('a').children('span').data('cod-estabelecimento');
var varArrayCampos = [];
var tipos = ['jpg', 'png', 'gif', 'psd', 'bmp', 'tif', 'pdf', 'xml'];
var nome = data.result.files[0].name;
var today = new Date();
var s = today.getSeconds();
var i = today.getMinutes();
var h = today.getHours();
var dd = today.getDate();
var mm = today.getMonth();
var yyyy = today.getFullYear();
now = '' + yyyy + mm + dd + h + i + s;
var filename = now + '.' + nome.substr(nome.lastIndexOf('.')+1);
$('.indexadores-campos .row input').each(function() {
var indexadoresData = {};
indexadoresData.nomCampo = $(this).attr('name');
indexadoresData.numOrdem = $(this).data('num-ordem');
indexadoresData.valor = $(this).val();
varArrayCampos.push(indexadoresData);
});
console.log(varCodTipoProcesso)
$.getJSON('/sistema/ajax/setUploadFileJson.php', {
arquivo: arquivo,
varCodProcesso: null,
varCodTipoProcesso: varCodTipoProcesso,
varCodEstabelecimento: varCodEstabelecimento,
varCodTipoDocumento: null,
varArrayCampos: varArrayCampos,
pasta: null,
tipos: tipos,
nome: filename
}).done(function(doc) {
console.log(data.codDocumento); //there's the data I want to add to the preview
}).fail(function() {
console.log('error');
});
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>').text('Upload server currently unavailable - ' + new Date()).appendTo('#fileupload');
});
}
// Load & display existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
I managed to get the data from the server, but douldn't add it to the preview and I can't figure out how to do it. Can anybody help me on this?
The answered is already available and both will work fine.
You need to use additional plugin jquery.fileupload-ui.js as mentioned in answer (https://stackoverflow.com/a/11016888/2871356) or as mentioned in answer(https://stackoverflow.com/a/18284685/2871356) Place this inside your add(e, data) callback function, adjusting for your own html elements accordingly:
$('body').append('<img src="' + URL.createObjectURL(data.files[0]) + '"/>');
my autocomplete works fine, but problem appears when I want to skip to another field in my form. When autocomplete lose focus its value disappears (also value of span that I render after this autocomplete disappears).
function initCaAutocomplete() {
$(".caSelector").autocomplete({
source: "/core/index/search-ca/ajax/1",
minLength: 2,
select: function (event, ui) {
var descId = 'desc_' + $(this).attr('id');
if ($('span#' + descId).length) {
$('span#' + descId).html(ui.item.desc);
$('span#' + descId).attr('title', ui.item.fullDesc);
} else {
$(this).after('<span title="' + (ui.item.fullDesc) + '" class="cpv_descHolder" id="' + descId + '">'
+ ui.item.fullDesc + '</span>');
}
ui.item.value = ui.item.code;
$('.tooltip', $(this).parent()).hide();
},
change: function (event, ui) {
var descId = 'desc_' + $(this).attr('id');
var inputId = $(this).attr('id');
var source = $(this).val();
$.ajax({
type : 'POST',
url : '/core/index/search-ca/ajax/1',
dataType: "text",
async : true,
data : {
term: source
},
success: function (response) {
var codes = $.parseJSON(response);
if (codes.length == 0) {
$('#' + inputId).val('');
$('span#' + descId).html('');
}
},
error: function (response) {
$('#' + inputId).val('');
$('span#' + descId).html('');
}
});
},
position: { my : "left top", at: "left bottom" }
});
}
In my MVC project, I have passed a list of users to my view, and inside this view I iterate through the list and create an anchor tag for each user. Would it be possible to add a delay after each anchor tag is created? Here is my jquery:
DeskFunction.prototype.init = function() {
var self = this;
var element;
this.allData = #Html.Raw(#JsonConvert.SerializeObject(Model.AllDeskData));
for (var i = 0; i < this.allData.length; i++) {
element = $("<a href='#' class='deskBtn tooltip fancybox' title='" + this.allData[i].Name + "' data-name='" + this.allData[i].UserName + "' data-department='" + this.allData[i].DepartmentName + "'></a>");
$(element).css({
"top": this.allData[i].DeskYCoord,
"left": this.allData[i].DeskXCoord
}).appendTo(".map").show('normal').delay(3000);
$(element).on('click', function() {
var user = $(this).attr("data-name");
$.ajax({
url: "/Home/GetUserData",
type: "GET",
data: { user: user },
success: function(data) {
$(".user-data .name").text(data.displayName);
}
});
});
}
$('.tooltip').tooltipster();
$('.search-user').keyup(function() {
self.search();
});
};
I would like the first tag to be created and added to the map, then a delay of a second, after that the next anchor tag would be added, is this possible? Any help would be appreciated
you can try below code. inside setTimeout write all code that you want to do under the loop. It will get called after 1 sec
for (var i = 0; i < this.allData.length; i++) {
(function(i, self ){
setTimeout(function(){
// ALL LOOP CODE HERE
// use self.allData
}, 1000);
}(i, self ));
}
You could place your code in a setTimeout.
DeskFunction.prototype.init = function() {
var self = this;
var element;
this.allData = #Html.Raw(#JsonConvert.SerializeObject(Model.AllDeskData));
for (var i = 0; i < this.allData.length; i++) {
element = $("<a href='#' class='deskBtn tooltip fancybox' title='" + this.allData[i].Name + "' data-name='" + this.allData[i].UserName + "' data-department='" + this.allData[i].DepartmentName + "'></a>");
$(element).css({
"top": this.allData[i].DeskYCoord,
"left": this.allData[i].DeskXCoord
}).appendTo(".map").show('normal');
setTimeout(function(){
$(element).on('click', function() {
var user = $(self).attr("data-name");
$.ajax({
url: "/Home/GetUserData",
type: "GET",
data: { user: user },
success: function(data) {
$(".user-data .name").text(data.displayName);
}
});
});
}, 3000);
}
$('.tooltip').tooltipster();
$('.search-user').keyup(function() {
self.search();
});
};
With timeouts incrementing and passing all data through a function call to a local scope the following could should do:
for(var i in this.allData) {
// create local function scope saving i and data from being altered by next iterations
(function(i, data) {
setTimeout(function() {
// place your code here, using data (and i)
}, i*1000);
})(i, this.allData[i]);
}
For each element of this.allData this.allData[i] is passed to the local function as data, along with each i. These are used in the inner scope for setting timeouts in intervalls of 1 sec and creating the anchor links.
You actually want an asynchronous loop:
DeskFunction.prototype.init = function() {
this.allData = #Html.Raw(#JsonConvert.SerializeObject(Model.AllDeskData));
var self = this,
allData = this.allData,
delay = 1000;
var appendDeleteLink = function appendDeleteLink(i) {
if (i >= allData.length) {
return;
}
var element = $("<a href='#' class='deskBtn tooltip fancybox' title='" + allData[i].Name + "' data-name='" + allData[i].UserName + "' data-department='" + allData[i].DepartmentName + "'></a>");
$(element).css({
"top": allData[i].DeskYCoord,
"left": allData[i].DeskXCoord
}).appendTo(".map").show('normal').delay(3000);
$(element).on('click', function() {
var user = $(this).attr("data-name");
$.ajax({
url: "/Home/GetUserData",
type: "GET",
data: { user: user },
success: function(data) {
$(".user-data .name").text(data.displayName);
}
});
});
(function(a) {
setTimeout(function() {
appendDeleteLink(a);
}, delay);
})(++i);
};
appendDeleteLink(0);
$('.tooltip').tooltipster();
$('.search-user').keyup(function() {
self.search();
});
};