I have a code on my header for creating som pop up
$(document).ready(function() {
//Lorsque vous cliquez sur un lien de la classe poplight et que le href commence par #
$('a.poplight[href^=#]').click(function() {
var popID = $(this).attr('rel'); //Trouver la pop-up correspondante
var popURL = $(this).attr('href'); //Retrouver la largeur dans le href
//Récupérer les variables depuis le lien
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //La première valeur du lien
//Faire apparaitre la pop-up et ajouter le bouton de fermeture
$('#' + popID).fadeIn().css({
'width': Number(popWidth)
})
.prepend('<img src="images/close_pop.png" class="btn_close" title="Fermer" alt="Fermer" />');
//Récupération du margin, qui permettra de centrer la fenêtre - on ajuste de 80px en conformité avec le CSS
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
//On affecte le margin
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
//Effet fade-in du fond opaque
$('body').append('<div id="fade"></div>'); //Ajout du fond opaque noir
//Apparition du fond - .css({'filter' : 'alpha(opacity=80)'}) pour corriger les bogues de IE
$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
return false;
});
//Fermeture de la pop-up et du fond
$('a.close, #fade').live('click', function() { //Au clic sur le bouton ou sur le calque...
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove(); //...ils disparaissent ensemble
});
return false;
});
});
I use also jquery on the head of my document
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
the trouble is that it return to me an error
Uncaught TypeError: undefined is not a function
exactly on the part where I shpould click for closing the popup
so I can open it but not close it.
Anykind of help will be much appreciated.
.live() was deprecated in jQuery 1.7, and removed in 1.9. You need to use .on() instead
$(document).on('click', 'a.close, #fade', function() { //Au clic sur le bouton ou sur le calque...
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove(); //...ils disparaissent ensemble
});
return false;
});
live is removed from jQuery 1.9, and you are using jQuery 1.10.2 => Error.
You can use on() to handle or use delegate to use Event Delegation.
Using bind, click to handle event directly.
on
$(document).on('click', 'a.close, #fade', function() { //Au clic sur le bouton ou sur le calque...
});
delegate
$(document).delegate('a.close, #fade','click', function() { //Au clic sur le bouton ou sur le calque...
});
click
$('a.close, #fade').click(function(){});
bind
$('a.close, #fade').bind("click",function(){});
Hope it'll help you.
Related
I have 2 google forms that record form responses to a google Spreadsheet File. Each form delivers the answers to its respective sheet or "tab".
I have written a script for each form that sends me an email whenever the form is submitted. I have tested them separately and they work. However, when I try to put them together, neither the sorting or the sending of the email work.
I am having a hard time debugging because the main function is run by a trigger and I use form response data in my script and thus cannot execute the function manually.
Code:
//this function is called every time a form is submitted
function procesarVinculacionORetiro(e){
//decide which of the two forms were submitted:
if (e.namedValues["Ingresa por?"]){
/////////
//////// VINCULACIONES
///////
//ordenar hoja de vinculaciones
//enviar correo con info ultima vinculacion
//sort data so new is always on top
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Vinculaciones');
var range = sheet.getRange("A2:X");
//column A = 1, B = 2, etc.
range.sort( { column : 1, ascending: false } );
//**********
//PARA EL CORREO, CALCULEMOS DATOS IMPORTANTES:
//**********
//esto arregla el problema de emails duplicados
Utilities.sleep(3000);
//e es un objeto que contiene la info del formato que acaban de submit
var dataset = e.values;
var timestamp=e.namedValues["Timestamp"];
var ingresaPor=e.namedValues["Ingresa por?"];
var cualTienda=e.namedValues["En cual tienda? o en oficina?"];
var cargo=e.namedValues["Que cargo va a desempeñar?"];
var nombreEmpleado=e.namedValues["Nombre de la persona a vincular? (OJO: sin apellidos)"];
var apellido1Empleado=e.namedValues["Apellido #1 de la persona a vincular?"];
var apellido2Empleado=e.namedValues["Apellido #2 de la persona a vincular?"];
var quienSolicita=e.namedValues["Como te llamas tu?"];
var quienAutoriza=e.namedValues["Quien lo autoriza?"];
//*********
//CONFIGUREMOS EL CUERPO DEL CORREO
//*********
var message='';
message="Hola Equipo, hay una nueva vinculacion pendiente por crear. Los datos completos estan en la hoja de Vinculaciones.<br/><br/> RESUMEN: <br/><br/> fecha de reporte: "+timestamp+"<br/> nombre: "+nombreEmpleado+" "+apellido1Empleado+" "+apellido2Empleado+"<br/>ingresa por: "+ingresaPor+"<br/>reportado por: "+quienSolicita+"<br/> dice que lo autoriza: "+quienAutoriza+"<br/>"
//configuremos header correo:
var destinatario='pamunoz#azucarcolombia.com';
//cuadremos cc
var carbonCopy='nomina#grupoimperio.com.co, jerodriguez#azucarcolombia.com, imalca#azucarcolombia.com';
var subject="#Vincular para "+cualTienda+" (" +cargo+"): "+ nombreEmpleado+" "+apellido1Empleado+" x "+ingresaPor + " x " + quienSolicita
MailApp.sendEmail({
to: destinatario,
cc: carbonCopy,
subject: subject,
htmlBody: message,
replyTo: 'nadie#azucarcolombia.com'
});
}
else {
/////////
//////// RETIROS
///////
//sort data so new is always on top
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Retiros');
var range = sheet.getRange("A2:I");
//column A = 1, B = 2, etc.
range.sort( { column : 1, ascending: false } );
//**********
//PARA EL CORREO, CALCULEMOS DATOS IMPORTANTES:
//**********
//esto arregla el problema de emails duplicados
Utilities.sleep(3000);
//*********
//CONFIGUREMOS EL CUERPO DEL CORREO
//*********
var message='';
message="Hola Equipo, hay un nuevo retiro pendiente, lo pueden ver en la hoja RETIROS. Favor gestionar pago liquidacion en cuanto antes. Gracias"
//configuremos header correo:
var destinatario='pamunoz#azucarcolombia.com';
//cuadremos cc
var carbonCopy='nomina#grupoimperio.com.co, jerodriguez#azucarcolombia.com, imalca#azucarcolombia.com';
var subject='#Retiro Nuevo';
MailApp.sendEmail({
to: destinatario,
cc: carbonCopy,
subject: subject,
htmlBody: message,
replyTo: 'nadie#azucarcolombia.com'
});
}
}
I'm looking for integrate a post-it application in my django website with Javascript/JQuery.
I found something as a tutorial and I tried to insert it in my script but I get SyntaxError :
SyntaxError: missing ; before statement post-it.js:2:19
I don't know Javascript langage so it's a bit complicated for me, but I don't see where ; is missing :/
This is my HTML post-it part :
<h1>Post-It</h1>
<input type="button" value="Ajouter un Post-It" id="btn-addNote" />
<div id="board"></div>
This is my Javascript file :
(function ($, $S) {
// $jQuery
// $S window.localStorage
// Déclaration des variables
var $board = $('#board'),
// Placement des Post-It
Postick, //Object Singleton contenant les fonctions pour travailler sur le LocalStorage
len = 0,
// Nombre d'objets dans le LocalStorage
currentNotes = »,
// Stockage du code HTML de l'élément Post-It
o; // Données actuelles du Post-It dans le localStorage
// Gérer les Post-It dans le LocalStorage
// Chaque objet est enregistré dans le localStorage comme un Object
Postick = {
add: function (obj) {
obj.id = $S.length;
$S.setItem(obj.id, JSON.stringify(obj));
},
retrive: function (id) {
return JSON.parse($S.getItem(id));
},
remove: function (id) {
$S.removeItem(id);
},
removeAll: function () {
$S.clear();
},
};
// S'il existe des Post-It on les créer
len = $S.length;
if (len) {
for (var i = 0; i < len; i++) {
// Création de tous les Post-It se trouvant dans le localStorage
var key = $S.key(i);
o = Postick.retrive(key);
currentNotes += '<div class="postick"';
currentNotes += ' style="left:' + o.left;
currentNotes += 'px; top:' + o.top;
// L'attribut data-key permet de savoir quelle note on va supprimer dans le localStorage
currentNotes += 'px"><div class="toolbar"><span class="delete" data-key="' + key;
currentNotes += '">x</span></div><div contenteditable="true" class="editable">';
currentNotes += o.text;
currentNotes += '</div></div>';
}
// Ajoute tous les Post-It sur le tableau de bord
$board.html(currentNotes);
}
// Dès que le document est chargé, on rend tous les Post-It Draggable
$(document).ready(function () {
$(".postick").draggable({
cancel: '.editable',
"zIndex": 3000,
"stack" : '.postick'
});
});
// Suppression du Post-It
$('span.delete').live('click', function () {
if (confirm('Etes vous sûr de vouloir supprimer cette note ?')) {
var $this = $(this);
// L'attribut data-key permet de savoir quelle note on va supprimer dans le localStorage
Postick.remove($this.attr('data-key'));
$this.closest('.postick').fadeOut('slow', function () {
$(this).remove();
});
}
});
// Création du Post-It
$('#btn-addNote').click(function () {
$board.append('<div class="postick" style="left:20px;top:70px"><div class="toolbar"><span class="delete" title="Fermer">x</span></div><div contenteditable class="editable"></div></div>');
$(".postick").draggable({
cancel: '.editable'
});
});
// Sauvegarde tous les Post-It lorsque l'utilisateur quitte la page
window.onbeforeunload = function () {
// Nettoyage du localStorage
Postick.removeAll();
// Puis on insère chaque Post-It dans le LocalStorage
// Sauvegarde la position du Post-It, afin de le replacer lorsque la page est chargée à nouveau
$('.postick').each(function () {
var $this = $(this);
Postick.add({
top: parseInt($this.position().top),
left: parseInt($this.position().left),
text: $this.children('.editable').text()
});
});
}
})(jQuery, window.localStorage);
Thank you :)
PS : I thing that the SyntaxError comes from there right : currentNotes = »,
Protip: When developing, keep indentations cool. You indentation here is a mess and is difficult to follow code blocks. I know you are new so don't worry, but just get used to have a clean indentation.
Now, if you get the code and run it, elsewhere (Chrome console, jsfiddle or whatever) it tells you the exact line where the error is happening, as is a SyntaxError and that kind of errors happens when the engine is checking the code, but not running it, so is not needed to have all the needed libs loaded along with the code.
If you check this fiddle: http://jsfiddle.net/8now04xs/1 In the console you will notice that the error comes from the line 54, and if you click on it (Being in CHrome DevTools) it will lead you directly to the line with the problem: http://i.imgur.com/G8tPl92.gifv
You were right, the error code comes from the line you said. The problem is that is not a string, nor a number or a valid keyword. Is a non-valid character.
I don't read all the code, but I guess that you want it to be a string. In JavaScript (and almost all languages), strings must be quoted with either single or double quote, like this:
currentNotes = "»",
If you look around the rest of the code, you will se a lot of strings following this pattern, so you can understand better how this works. If you want it to be an empty string then you have to it right this:
currentNotes = "",
If you look closely, it makes sense.
After fixing this error, the fiddle will fail, as it will try to run the code and encounter a lot of problems because not running in your Django environment.
I check your code on jshint.
There is 2 problem.
1 . Quote '»' [I already mention about this on comment.]
Missing ;
}; // Missing ; in this line.
})(jQuery, window.localStorage);
I am trying to include jquery to my cordova project. But when compiling I get this error. I don't really know what that means.
EROOR : http://prntscr.com/bk4dn3
HTML INCLUDES : http://prntscr.com/bk4fnn
And the code that is using jquery:
$.stringBuilder = function () {
this.buffer = [];
};
$.stringBuilder.prototype = {
cat: function (what) {
this.buffer.push(what);
return this;
},
string: function () {
return this.buffer.join('');
},
reset: function(){
this.buffer = [];
}
};
var questions = ["Si tout va bien je compte prendre ma retraite dans ...",
"Comment pourrais-je qualifier ma situation financière actuelle ?",
"Notre revenu familial annuel actuel (rentes comprises) avant impôt se situe…",
"Je voudrais pouvoir suivre l’évolution des rendements sur mes placements...",
"Je sais qu’il est recommandé d’avoir de l’argent en réserve pour faire face aux imprévus (exemple : une perte ou une diminution de revenu). De combien de mois de revenu familial net disposons-nous actuellement ?"
];
var html = new $.stringBuilder();
for (var i in questions)
html.cat("<tr><td>").cat("<b>" + (i++) + ". </b>").cat("</td> <td>").cat(i).cat("</td></tr>");
while ($('#questionnaire').firstChild) {
$('#questionnaire').removeChild($('#questionnaire').firstChild);
}
$('#questionnaire').append(html.string());
In my Meteor app, I have a method that reads in a .csv file and inserts it into a collection. This file is in Spanish, and so includes characters like ó (ó). Within the method, I am running console.log(row[3][9] + ' is ' + row[3].charCodeAt(9)); which works fine unless it is a special character, in which case I always get "? is 65533" in the console. I'm not very familiar with character encoding methods, but am confused as to why this would be encoded at all since it is coming from a .csv file.
A sample of the file:
1,1,1,"Apreciación de directivos, profesores, estudiantes y personal administrativo sobre la claridad en los objetivos del programa",Encuesta Realizada,,,,,,,4.30,b
1,1,2,"Apreciación de directivos, profesores, estudiantes, visitantes y personal administrativo de la capacidad que ha demostrado el programa a lo largo de su trayectoria para lograr dichos objetivos ",Encuesta Realizada,,,,,,,3.97,v
2,2,3,Existencia de evidencia de los proceso de selección de estudiantes con criterios bien definidos en los últimos 5 años. ,Actas de admisión Reglamento general reglamento estudiantil Documento Maestro ,,,,,,,4.54,b
2,2,4,Existencia de evidencia de estrategias implementadas en los últimos 5 años para asegurar un número de estudiantes adecuado que le den sostenibilidad al programa.,Página web folletos Resoluciones de las universidades de apoyos a estudiantes Solicitudes al consejo de Rectores ,,,,,,,4.00,b
the JavaScript method being used to upload and read-in the file:
Meteor.methods({
'uploadFile':function(fileid,filename){
var fs = Meteor.npmRequire('fs');
var file = Uploads.find({_id:fileid});
var listNewAll = [];
Meteor.setTimeout(function(){
var filepath = '/imports/uploads' + '-' + fileid + '-' + filename;
CSV().from.stream(
fs.createReadStream(filepath),
{'escape':'\\'})
.on('record', Meteor.bindEnvironment(function(row,index){
fullList.insert({
'Factor':row[0],
'Caracteristica':row[1],
'Number':row[2],
'Indicador':row[3],
'Razon':row[4],
'UA':row[5],
'UC':row[6],
'UM':row[7],
'UCe':row[8],
'UCo':row[9],
'US':row[10],
'Tot':row[11],
'Color':row[12],
})
console.log(row[3][9] + ' is ' + row[3].charCodeAt(9));
console.log(row[3].charCodeAt(9) == 243);
}, function(error){
console.log(error);
}))
.on('error', function(err){
console.log(err);
})
.on('end', function(count){
})
},100);
}
})
I'm developing a cross platform application using Appcelerator Titanium.
I'm going to fire logout method when user clicks Android back button, in the next windows after login window.
Everything works, but the second time I tried to login and then logout alert dialog shows up two time.
Hope someone will help. Giacomo.
var win = Titanium.UI.currentWindow;
var msg = Titanium.UI.createLabel({
text:"Mail: " + win.email + "\nNome: " + win.name,
top:10,
left:10,
width:300,
height:'auto'
});
win.add(msg);
//definisco una finestra di dialogo per informare l'utente sul logout
var dialog = Ti.UI.createAlertDialog({
buttonNames: ['Si', 'No'],
message: 'Vuoi effettuare il logout?',
title: 'Attenzione'
});
//intercetto il tasto indietro di android e gestisco il Logout
var listener = win.addEventListener('android:back',function(e){
//aggiungo un event listener alla finestra di dialogo intercettando il tasto si o no
dialog.show();
dialog.addEventListener('click', function(e){
if (e.index == 1){
//è stato cliccato il tasto NO, quindi nessuna azione
}else if(e.index == 0){
//è stato cliccato il tasto Si, quindi effettuo il logout, cancello la variabile di sessione ...
win.close();
win.remove(msg);
win.remove(dialog);
}
});
});
I have pulled your answer out of the question and posted it here. This will allow future users to more easily see your solution.
The solution end up being this code
var handlerBack = function (e){
//aggiungo un event listener alla finestra di dialogo intercettando il tasto si o no
dialog.show();
dialog.addEventListener('click', function(e){
if (e.index == 1){
//è stato cliccato il tasto NO, quindi nessuna azione
}else if(e.index == 0){
//è stato cliccato il tasto Si, quindi effettuo il logout, cancello la variabile di sessione ...
win.close();
win.remove(msg);
win.remove(dialog);
win.removeEventListener('android:back', handlerBack);
}
});
};
win.addEventListener('android:back', handlerBack);