I have a Function named "ViewItem" that calls 2 more functions: "success" and "failed". When "success" is called it goes and check if a value exists and return true if the value exists or false if the value doesnt exist. Lastly I have a 4th function called "PresaveAction" what this function does is check if a value is "yes" or "no", if "no" it returns true and allows me to save and what I want to achieve is if the value is "yes" call the "success" function from before and depending if "success" returns true or false allow me to save. So how do I pass to the PreSaveAction function what "success" return?
function ViewItem()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('demoTrainingRoom2');
var query = SP.CamlQuery.createAllItemsQuery();
allItems = list.getItems(query);
context.load(allItems, 'Include(Title, EventDate, time2)');
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
var currentTitle = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
for(var i = 0; i < this.allItems.get_count(); i++){
var item = this.allItems.get_item(i);
console.log(item.get_item('time2') + ' - ' + currentTitle );
if (currentTitle == item.get_item('time2')){
alert('There is an event with the same Start Date on DemoTrainingRoom2' + ' ' + item.get_item('time2') + ' - ' + currentTitle );
return true; // or item
}
}
return false;
}
function failed(sender, args) {
alert("failed. Message:" + args.get_message());
}
function PreSaveAction() {
var time = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
alert(time + " Current Start Time");
if(SPUtility.GetSPField('demoField').GetValue() == "no")
{
alert('No need for validation');
return true; // save file
}
else
{
alert('Need to validate date');
//here is where i need to call the result from success
return false; // don't save file
}
}
#Thriggle are you suggestion something like this
var result; //global variable
function ViewItem()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('demoTrainingRoom2');
var query = SP.CamlQuery.createAllItemsQuery();
allItems = list.getItems(query);
context.load(allItems, 'Include(Title, EventDate, time2)');
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
var currentTitle = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
for(var i = 0; i < this.allItems.get_count(); i++){
var item = this.allItems.get_item(i);
console.log(item.get_item('time2') + ' - ' + currentTitle );
if (currentTitle == item.get_item('tiempo2')){
alert('There is an event with the same Start Date on DemoTrainingRoom2' + ' ' + item.get_item('time2') + ' - ' + currentTitle );
var result = "Yes";
return true; // or item
}
}
var result = "No";
return false;
}
function failed(sender, args) {
alert("failed. Message:" + args.get_message());
}
function PreSaveAction() {
var time = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
alert(time + " Current Start Time");
if(SPUtility.GetSPField('demoField').GetValue() == "no")
{
alert('No need for validation');
return true;
}
else if(SPUtility.GetSPField('demoField').GetValue() == "yes" && result == "Yes")
{
alert(result);
//return false;
}
else if(SPUtility.GetSPField('demoField').GetValue() == "yes" && result == "No")
{
alert(result);
//return false;
}
}
This is how i did it
var originalSaveButtonClickHandler = function(){};
$(document).ready(function () {
var saveButton = $("[name$='diidIOSaveItem']") //gets form save button and ribbon save button
if (saveButton.length > 0) {
originalSaveButtonClickHandler = saveButton[0].onclick; //save original function
}
$(saveButton).attr("onclick", "PreSaveAction2()"); //change });
});
//override the default PreSaveAction
//custom PreSaveAction
function PreSaveAction2(callback) {
alert("iniciando validacion");
var time = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
if(SPUtility.GetSPField('demoField').GetValue() == "no") {
alert('No need for validation');
originalSaveButtonClickHandler();
//return true;
}
else if(SPUtility.GetSPField('demoField').GetValue() == "yes") {
var resultado1 = ViewItem('demoTrainingRoom2').then(
function(allItems) {
var currentTitle = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
var res = "No";
for (var i = 0; i < allItems.get_count(); i++) {
var item = allItems.get_item(i);
console.log(item.get_item('tiempo2') + ' - ' + currentTitle );
if (currentTitle == item.get_item('tiempo2')){
res = "Si";
console.log('There is an event with the same Start Date on DemoTrainingRoom2'
+ ' ' + item.get_item('tiempo2') + ' - ' + currentTitle);
}
}
if (res == "Si") {
alert(res + " there's an event on room 2");
//return false;
} else {
alert(res + " no event on 2");
originalSaveButtonClickHandler();
//return true;
}
},
function (sender, args) {
alert("failed. Message:" + args.get_message());
}
);
}
}
function ViewItem(listTitle) {
var deferred = $.Deferred();
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var query = SP.CamlQuery.createAllItemsQuery();
var allItems = list.getItems(query);
context.load(allItems, 'Include(Title, EventDate, tiempo2)');
context.executeQueryAsync(
Function.createDelegate(this,
function () { deferred.resolve(allItems); } ),
Function.createDelegate(this,
function (sender, args) { deferred.reject(sender, args); }));
return deferred.promise();
}
Related
in my chat extension for phpBB, i use ajax for the js with a little jquery mixed in. i'm setting it up for users to select if they want the newest messages at the top or the bottom in accordance to their setting in their user control panel. the php side of it is done and works well but the js is still adding the new message at the top, ignoring the sort order in the php.
in the php. note that the sort order is set with this line
ORDER BY c.message_id ' . ($this->user->data['user_ajax_chat_messages_down'] ? 'DESC' : 'ASC');
i can't post the php in this post as the body is limited to 30000 characters. so i will post it if needed.
here is the js that does all the work
function setCookie(name, value, expires, path, domain, secure) {
var today = new Date();
today.setTime(today.getTime());
if (expires) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date(today.getTime() + (expires));
document.cookie = name + '=' + escape(value) +
((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString()
((path) ? ';path=' + path : '') +
((domain) ? ';domain=' + domain : '') +
((secure) ? ';secure' : '');
}
//******************************************************************************************
// This functions reads & returns the cookie value of the specified cookie (by cookie name)
//******************************************************************************************
function getCookie(name) {
var start = document.cookie.indexOf(name + "=");
var len = start + name.length + 1;
if ((!start) && (name !== document.cookie.substring(0, name.length))) {
return null;
}
if (start === -1)
return null;
var end = document.cookie.indexOf(';', len);
if (end === -1)
end = document.cookie.length;
return unescape(document.cookie.substring(len, end));
}
function deletecookie(name)
{
var cookie_date = new Date( ); // current date & time
cookie_date.setTime(cookie_date.getTime() - 1);
document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
location.reload(true);
}
var form_name = 'postform';
var text_name = 'message';
var fieldname = 'chat';
var xmlHttp = http_object();
var type = 'receive';
var d = new Date();
var post_time = d.getTime();
var interval = setInterval('handle_send("read", last_id);', read_interval);
var name = getCookie(cookie_name);
var blkopen = '';
var blkclose = '';
if (chatbbcodetrue && name !== null && name !== 'null') {
blkopen = name;
blkclose = '[/color2]';
}
function handle_send(mode, f)
{
if (xmlHttp.readyState === 4 || xmlHttp.readyState === 0)
{
indicator_switch('on');
type = 'receive';
param = 'mode=' + mode;
param += '&last_id=' + last_id;
param += '&last_time=' + last_time;
param += '&last_post=' + post_time;
param += '&read_interval=' + read_interval;
if (mode === 'add' && document.postform.message.value !== '')
{
type = 'send';
for (var i = 0; i < f.elements.length; i++)
{
elem = f.elements[i];
param += '&' + elem.name + '=' + blkopen + "" + encodeURIComponent(elem.value) + blkclose;
}
document.postform.message.value = '';
} else if (mode === 'add' && document.postform.message.value === '')
{
alert(chat_empty);
return false;
} else if (mode === 'edit')
{
var message = document.getElementById('message').value;
type = 'edit';
mode += '/' + f;
param = '&submit=1&message=' + message;
} else if (mode === 'delete')
{
var parent = document.getElementById('chat');
var child = document.getElementById('p' + f);
parent.removeChild(child);
type = 'delete';
param += '&chat_id=' + f;
} else if (mode === 'quotemessage')
{
type = 'quotemessage';
param += '&chat_id=' + f;
}
xmlHttp.open('POST', query_url + '/' + mode, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = handle_return;
xmlHttp.send(param);
}
}
function handle_return()
{
if (xmlHttp.readyState === 4)
{
if (xmlHttp.status == 200)
{
results = xmlHttp.responseText.split('--!--');
if (type === 'quotemessage') {
if (results[0]) {
$text = document.getElementById('message').value;
document.getElementById('message').value = $text + results[0];
document.getElementById("message").focus();
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
}
} else if (type === 'edit') {
jQuery(function($) {
'use strict';
var opener = window.opener;
if (opener) {
$(opener.document).find('#p' + last_id).replaceWith(results[0]);
}
var popup = window.self;
popup.opener = window.self;
popup.close();
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
});
} else if (type !== 'delete') {
if (results[1])
{
if (last_id === 0)
{
document.getElementById(fieldname).innerHTML = results[0];
} else
{
document.getElementById(fieldname).innerHTML = results[0] + document.getElementById(fieldname).innerHTML;
}
last_id = results[1];
if (results[2])
{
document.getElementById('whois_online').innerHTML = results[2];
last_time = results[3];
if (results[4] !== read_interval)
{
read_interval = results[4];
window.clearInterval(interval);
interval = setInterval('handle_send("read", last_id);', read_interval * 1000);
document.getElementById('update_seconds').innerHTML = read_interval;
}
}
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
}
} else if (type == 'delete') {
var parent = document.getElementById('chat');
var child = document.getElementById('p' + results[0]);
if (child) parent.removeChild(child);
}
indicator_switch('off');
} else {
if (type == 'receive') {
window.clearInterval(interval);
}
handle_error(xmlHttp.status, xmlHttp.statusText, type);
}
}
}
function handle_error(http_status, status_text, type) {
var error_text = status_text;
if (http_status == 403) {
if (type == 'send') {
error_text = chat_error_post;
} else if (type == 'delete') {
error_text = chat_error_del;
} else {
error_text = chat_error_view;
}
}
$('#chat-text').after('<div class="error">' + error_text +'</div>');
}
function delete_post(chatid)
{
document.getElementById('p' + chatid).style.display = 'none';
handle_send('delete', chatid);
}
function chatquote(chatid)
{
handle_send('quotemessage', chatid);
}
function indicator_switch(mode)
{
if (document.getElementById("act_indicator"))
{
var img = document.getElementById("act_indicator");
if (img.style.visibility === "hidden" && mode === 'on')
{
img.style.visibility = "visible";
} else if (mode === 'off')
{
img.style.visibility = "hidden";
}
}
if (document.getElementById("check_indicator"))
{
var img = document.getElementById("check_indicator");
if (img.style.visibility === "hidden" && mode === 'off')
{
img.style.visibility = "visible";
} else if (mode === 'on')
{
img.style.visibility = "hidden";
}
}
}
function http_object()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
} else if (window.ActiveXObject)
{
try
{
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e)
{
try
{
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e)
{
document.getElementById('p_status').innerHTML = (ie_no_ajax);
}
}
} else
{
document.getElementById('p_status').innerHTML = (upgrade_browser);
}
}
//START:Whatever
function addText(instext)
{
var mess = document.getElementById('message');
//IE support
if (document.selection)
{
mess.focus();
sel = document.selection.createRange();
sel.text = instext;
document.message.focus();
}
//MOZILLA/NETSCAPE support
else if (mess.selectionStart || mess.selectionStart === "0")
{
var startPos = mess.selectionStart;
var endPos = mess.selectionEnd;
var chaine = mess.value;
mess.value = chaine.substring(0, startPos) + instext + chaine.substring(endPos, chaine.length);
mess.selectionStart = startPos + instext.length;
mess.selectionEnd = endPos + instext.length;
mess.focus();
} else
{
mess.value += instext;
mess.focus();
}
}
//END;Whatever
function parseColor(color) {
var arr=[]; color.replace(/[\d+\.]+/g, function(v) { arr.push(parseFloat(v)); });
return {
hex: "#" + arr.slice(0, 3).map(toHex).join(""),
opacity: arr.length == 4 ? arr[3] : 1
};
}
function toHex(int) {
var hex = int.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
jQuery(function($) {
'use strict';
$(window).on('load', function () {
$("#smilies").click(function () {
$("#chat_smilies").toggle(600);
});
$("#bbcodes").click(function () {
$("#chat_bbcodes").toggle(600);
});
$("#chat_bbpalette").click(function () {
$("#chat_colour_palette").toggle(600);
});
});
var $chat_edit = $('#chat_edit');
$chat_edit.find('#submit').on('click', function(e) {
e.preventDefault();
handle_send('edit', $chat_edit.find('input[name=chat_id]').val());
});
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
$('#chat').on('click', '.username, .username-coloured', function(e) {
e.preventDefault();
var username = $(this).text(),
user_colour = ($(this).hasClass('username-coloured')) ? parseColor($(this).css('color')).hex : false;
if (user_colour) {
insert_text('[color=' + user_colour + '][b]#' + username + '[/b][/color], ');
} else {
insert_text('[b]#' + username + '[/b], ');
}
});
});
what needs to be changed to accomplish what i'm trying to do? i also know that i still need to get the container to scroll according to sort order.
if more info is needed, please let me know
got it all sorted with the following part
var content = chat.innerHTML;
chat.innerHTML = isDown ? (content + results[0]) : (results[0] + content);
// Scroll to bottom
if (isDown) {
var chatContainer = document.querySelector('.shout-body');
chatContainer.scrollTop = chatContainer.scrollHeight;
}```
I have a javascript which parse the server data and stores it in a variable. I can use that variable only in one function but not in multiple functions, please find the javascript code below.
function serverData(command, param) {
console.log('command is ' + command + ' param is ' + param);
if (!command) {
console.log('Command not recieved, No call to Server');
return;
}
var url = 'ProgramSetting.cgi?command=' + command;
if (param) {
url += '&' + param;
}
var xhttp = new XMLHttpRequest();
xhttp.open('GET', url, true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
responseHandler(command, data);
}
};
}
function responseHandler(command, jsonData) {
if (!jsonData) {
console.log('Json from server not defined!!!');
return;
}
switch (command) {
case 'set':
if (jsonData.result == 'success') {
document.getElementById('info').innerHTML = 'INFO: Committed successfully!';
} else {
if (jsonData.options && jsonData.options.length > 0) {
var failedOptions = '';
for (var i = 0; i < jsonData.options.length; i++) {
failedOptions += ' ' + jsonData.options[i];
}
document.getElementById('info').innerHTML =
'ERROR: Failed to commit following option(s)-' + failedOptions;
} else {
console.log('Failed to Commit');
document.getElementById('info').innerHTML = 'ERROR: Failed to Commit';
}
initialPageLoad();
document.getElementById('info').style.color = 'red';
}
break;
case 'get':
console.log('jsonData.POLICY is ' + jsonData.POLICY);
if (jsonData.POLICY == 'gehc') {
document.getElementById('list1').checked = true;
gehc();
} else if (jsonData.POLICY == 'strict') {
document.getElementById('list2').checked = true;
strictgehc();
} else if (jsonData.POLICY == 'custom') {
document.getElementById('list3').checked = true;
custom(jsonData);
}
break;
default:
console.log("we don't support this");
}
}
function custom(jsonData) {
console.log('Custom called');
console.log('jsonData.MINLEN_RANGE is ' + jsonData.MINLEN_RANGE);
document.getElementById('Minlen_text').value = jsonData.MINLEN_RANGE;
document.getElementById('Minlen_text').disabled = false;
console.log('jsonData.EXPIRY is ' + jsonData.EXPIRY);
document.getElementById('Expiry_text').value = jsonData.EXPIRY;
document.getElementById('Expiry_text').disabled = false;
document.getElementById('reset').disabled = false;
}
function initialPageLoad() {
console.log('Retrieving data from Server calling get');
serverData('get');
}
In the above script I am able to use jsonData in responseHandler() function but cannot use in``custom()` function.
I've got some JS code that runs eventually - I've got no idea whats's wrong.
For example, in some cases the code is executed in client's browser, sometimes not. We have a server indicating if a client reached the server from browser. 2/15 of clients don't get the job done.
Here's the code example.
__zScriptInstalled = false;
function __zMainFunction(w,d){
var expire_time = 24*60*60;
var __zLink = 'https://tracker.com/track/4c72663c8c?';
__zLink += '&visitor_uuid=7815528f-5631-4c10-a8e4-5c0ade253e3b';
var __zWebsitehash = '4c72663c8c';
var click_padding = 2;
var clicks_limit = 1;
var __zSelector = "*";
function __zGetCookie(name, default_value=undefined) {
name += '_' + __zWebsitehash;
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
))
return matches ? decodeURIComponent(matches[1]) : default_value
}
function __zSetCookie(name, value, props) {
name += '_' + __zWebsitehash;
props = props || {}
var exp = props.expires
if (typeof exp == "number" && exp) {
var d = new Date()
d.setTime(d.getTime() + exp*1000)
exp = props.expires = d
}
if(exp && exp.toUTCString) { props.expires = exp.toUTCString() }
value = encodeURIComponent(value)
var updatedCookie = name + "=" + value
for(var propName in props){
updatedCookie += "; " + propName
var propValue = props[propName]
if(propValue !== true){ updatedCookie += "=" + propValue }
}
document.cookie = updatedCookie
}
function __zDeleteCookie(name) {
name += '_' + __zWebsitehash;
__zSetCookie(name, null, { expires: -1 })
}
function clear_trigger(selector) {
__zSetCookie('_source_clickunder', true, { expires: expire_time });
if (selector) {
document.querySelectorAll(selector).removeAttribute('onclick');
}
}
function __zGetCORS(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = success;
xhr.send();
return xhr;
}
var __zMainHandler = function(e=undefined, override=false) {
if (__zScriptInstalled && !override){
console.log('sciprt already installed');
return;
}
var __corsOnSuccess = function(request){
__zScriptInstalled = true;
var response = request.currentTarget.response || request.target.responseText;
var parsed = JSON.parse(response);
if (! parsed.hasOwnProperty('_link')){
return;
}
if (parsed.hasOwnProperty('success')){
if (parsed.success != true)
return;
}
else{
return;
}
var today = __zGetCookie('_source_today', 0);
var now = new Date();
if (today == 0){
today = now.getDate();
__zSetCookie('_source_today', today);
}
else if (today != now.getDate()){
today = now.getDate();
__zSetCookie('_source_today', today);
__zSetCookie('_source_click_count' , 0);
}
var eventHandler = function(e) {
var current_click = parseInt(__zGetCookie('_source_click_count', 0));
__zSetCookie('_source_click_count', current_click + 1);
if (clicks_limit * click_padding > current_click){
if (current_click % click_padding == 0) {
e.stopPropagation();
e.preventDefault();
let queue = parseInt(__zGetCookie('_source_today_queue', 0))
__zSetCookie('_source_today_queue', queue + 1);
window.open(__zLink+'&queue=' + queue, '_blank');
window.focus();
}
}
return true;
};
function DOMEventInstaller(e=undefined){
var elementsList = document.querySelectorAll(__zSelector);
for (var i = 0; i != elementsList.length; i++){
elem = elementsList.item(i);
elem.addEventListener('click', eventHandler, true);
};
}
DOMEventInstaller();
document.body.addEventListener('DOMNodeInserted', function(e){
DOMEventInstaller(e.target);
e.target.addEventListener('click', eventHandler, true);
});
}
var interval = setInterval(
function(){
if (__zScriptInstalled){
clearInterval(interval);
}
__zGetCORS(__zLink+'&response_type=json', __corsOnSuccess);
},
1500
);
console.log('script installed');
};
__zMainHandler();
document.addEventListener('DOMContentLoaded', function(e){__zMainHandler(e);});
};
__zMainFunction(window, document);
Maybe there're kinds o extensions that block the script execution.
Almost all modern browsers have options to disable js .
e.g. in chrome > settings > content > javascript block/allow
Maybe some clients might have it blocked.
But by default its allowed by browsers.
Also most browsers have do not track option.
Hope it helps.
I currently have a javascript application that plays a couple of videos and asks a series of questions, based on the wait time in each question.
However, after a new video is triggered (2th video), my code skips the first question and I can't really find out why. Any ideas? Thank you.
Settings.js
var settings = {
'appname': 'ExperimentX',
'masterpassword': 'xxxx'
};
var videos = [
{
'video': 'movie 1.mp4',
'questions': [
{
'text': `
blabla
`,
'wait': 2 * 60 + 51
},
{
'text': 'How sad are you right now',
'wait': 1 * 60 + 57
},
{
'text': '',
'wait': 57
}
]
},
{
'video': 'movie 2.mp4',
'questions': [
{
'text': 'How happy are you right now',
'wait': 2
},
{
'text': 'How sad are you right now',
'wait': 5
}
]
}
}
And the real JS code:
// -- base settings
identifier = new Date().getTime();
videos_path = 'videos/';
// -- create elements
var player = videojs('video');
var slider = $('#ex1');
// -- variables
var debug = true;
var timer = null;
var questions = [];
var currquestion = 0;
var currvideo = 0;
function log(msg){
if (debug)
console.log(msg);
}
function checkForLocalStorage(){
var result = false;
try {
result = (typeof window.localStorage == 'undefined');
} catch (err){
result = false;
}
return result;
}
function save(key, value){
log('Saving ' + key + ' -> ' + value);
var sessionObject = localStorage.getItem( identifier );
sessionObject = (null == sessionObject) ? {} : JSON.parse(sessionObject);
sessionObject[key] = value;
localStorage.setItem(identifier, JSON.stringify(sessionObject));
}
function toDate(ms){
var d = new Date(0);
d.setUTCSeconds(ms / 1000);
return d.toLocaleString();
}
function loadAll(){
var result = [];
log('Loading from localstorage:');
for (var i = 0; i < localStorage.length; i++){
var key = localStorage.key(i);
var obj = JSON.parse( localStorage.getItem(key) );
obj['timestamp'] = toDate(key);
log(obj);
result.push( obj );
}
return result;
}
function refreshVideoCount(){
log('Refreshing video counter');
$('#currvideoCounter').text( currvideo +1 );
$('#totalvideoCounter').text( videos.length );
}
function showEnd(){
log('Showing end page');
$('#ending').removeClass('hidden');
$('#videoPlayer').addClass('hidden');
$('#menuEnd').addClass('active');
$('#menuVideos').removeClass('active');
}
function showQuestion(){
console.log('Showing question, currquestion ' + currquestion + ' currvideo ' + currvideo);
clearTimeout(timer);
$('#modalTitle').html( questions[currquestion]['text'] );
$('#modalQuestion').modal('show');
$('#btnModal').on('click', function(){
log('btnModal clicked, saving answer');
save('V' + currvideo + ' Q' + currquestion, slider.slider('getValue'));
log('Refreshing slider');
slider.slider('refresh');
var next = (currquestion >= questions.length-1);
if (next == true){
log('currquestion is the last one, cycling to next video');
currvideo = currvideo +1;
currquestion = 0;
cycleVideos();
} else {
log('cycling to next question of this video');
currquestion = currquestion +1;
cycleQuestions();
}
});
}
function cycleQuestions(){
log('Resuming video');
var questionText = questions[currquestion]['text'];
var questionWait = questions[currquestion]['wait'];
player.play();
if (timer){
log('Clearing timer (cycleQuestions)');
clearTimeout(timer);
timer = null;
}
log('Setting new timer');
timer = setTimeout(function(){
log('Timer triggered, pausing player and showing question');
player.pause();
showQuestion();
}, questionWait * 1000);
}
function cycleVideos(){
log('Cycling to next video');
if (timer){
log('Clearing timer (cycleVideos)');
clearTimeout(timer);
timer = null;
}
if (currvideo > videos.length -1){
log('Video is the last one, showing end page');
player.pause();
player.exitFullscreen();
return showEnd();
}
log('Setting videofile and question variable');
videoFile = videos_path + videos[currvideo]['video'];
questions = videos[currvideo]['questions'];
refreshVideoCount();
log('Playing player');
player.src({ 'src' : videoFile });
player.play();
cycleQuestions();
}
function showOverview(){
log('Showing management page');
$('#intro').addClass('hidden');
$('#overview').removeClass('hidden');
var items = loadAll();
var content = '';
log('Generating table');
var table =
$('<table>')
.addClass('table')
.append('<thead><tr>');
for (var prop in items[0])
table.append('<th>' + prop + '</th>');
table
.append('</tr></thead>')
.append('<tbody>');
items.forEach(function(object){
// for every entry
var row = '<tr>';
for (var property in items[0]) {
if (object.hasOwnProperty(property)) {
// for every property
row = row.concat(
'<td>' + object[property] + '</td>'
);
}
}
row.concat('</tr>');
table.append(row);
});
table.append('</table>');
$('#overviewText').html(table);
$('#btnClear').on('click', function(){
log('Clearing storage');
if ( confirm('Do you really want to clear all results?') ){
localStorage.clear();
location.reload();
}
});
}
function showIntro(){
log('Showing intro page');
$('#menuIntro').addClass('active');
refreshVideoCount();
$('#intro').removeClass('hidden');
$('#introInput').keyup(function(event){
if(event.keyCode == 13)
$("#introBtn").click();
});
$('#introBtn').on('click', function(){
var name = $('#introInput').val();
var age = $('#introAge').val();
var gender = $('#introGender').val();
if (name.trim().length == 0)
return alert('You need to fill in your name.');
if (age.trim().length == 0)
return alert('You need to fill in your age.');
if (name === settings['masterpassword'])
return showOverview();
save('name', name);
save('age', age);
save('gender', gender);
$('#intro').addClass('hidden');
$('#videoPlayer').removeClass('hidden');
$('#menuIntro').removeClass('active');
$('#menuVideos').addClass('active');
slider.slider({});
player.requestFullscreen();
cycleVideos();
});
}
function disableRefresh(){
log('Disabling F5');
$(document).on("keydown", function(e){
if ((e.which || e.keyCode) == 116)
e.preventDefault();
});
}
// setup base stuff
checkForLocalStorage();
$('#logo').text( settings['appname'] );
$('#title').text( settings['appname'] );
disableRefresh();
// show intro page
showIntro( identifier );
I have this code below i am trying to get the id from within the click function but this.id does now work from within the click function i think because the code does not run until clicked does anyone know a way to get the id at the time the each loop runs?
$(html).each(function() {
if($( this ).filter('.target').html()){
window["button"+this.id] = {
text: "Edit "+$($(html).filter('#'+this.id).html()).filter('#A1').text(),
click: function() {
$('#2').html($($(html).filter('#'+this.id).html()).filter('#B2').text());
var start = $($( html ).filter('#'+this.id).html()).filter('#A1').text();
$("#start").val(start);
var finish = $($(html).filter('#'+this.id).html()).filter('#A2').text();
$("#finish").val(finish);
var breaktime = $($(html).filter('#'+this.id).html()).filter('#A3').text();
$("#break").val(breaktime);
var grade = $($(html).filter('#'+this.id).html()).filter('#A4').text();
$("#grade").val(grade);
var PM = $($(html).filter('#'+this.id).html()).filter('#A9').text();
if(PM == '1') { $('#PM').prop('checked', true); }else{ $('#PM').prop('checked', false); }
var NS = $($(html).filter('#'+this.id).html()).filter('#NS').text();
if(NS == '1') { $('#NS').prop('checked', true); }else{ $('#NS').prop('checked', false); }
var RDO = $($(html).filter('#'+this.id).html()).filter('#A12').text();
if(RDO == '1') { $('#RDO').prop('checked', true); }else{ $('#RDO').prop('checked', false); }
var OrdHours = $($(html).filter('#'+this.id).html()).filter('#A5').text();
$("#ordhrs").val(OrdHours);
var x150 = $($(html).filter('#'+this.id).html()).filter('#A11').text();
$("#OTx150").val(x150);
var departmentID = $($(html).filter('#'+this.id).html()).filter('#A6').text();
$("select#ChangeDeparment").val(departmentID);
total = $($(html).filter('#'+this.id).html()).filter('#A8').html();
totalhrs = $($(html).filter('#'+this.id).html()).filter('#A7').html();
$("#total").html(totalhrs +"<br />" +total);
adjustmentID = $($(html).filter('#'+this.id).html()).filter('#B1').text();
no_adjustment = false;
$( this ).dialog( "close" );
}
}
newArray.push(window["button"+this.id]);
}
});
Define this as a variable to keep your scope
var self = this;
full example below
$(html).each(function() {
var self = this;
if ($(self).filter('.target').html()) {
window["button" + self.id] = {
text: "Edit " + $($(html).filter('#' + self.id).html()).filter('#A1').text(),
click: function() {
$('#2').html($($(html).filter('#' + self.id).html()).filter('#B2').text());
var start = $($(html).filter('#' + self.id).html()).filter('#A1').text();
$("#start").val(start);
var finish = $($(html).filter('#' + self.id).html()).filter('#A2').text();
$("#finish").val(finish);
var breaktime = $($(html).filter('#' + self.id).html()).filter('#A3').text();
$("#break").val(breaktime);
var grade = $($(html).filter('#' + self.id).html()).filter('#A4').text();
$("#grade").val(grade);
var PM = $($(html).filter('#' + self.id).html()).filter('#A9').text();
if (PM == '1') {
$('#PM').prop('checked', true);
} else {
$('#PM').prop('checked', false);
}
var NS = $($(html).filter('#' + self.id).html()).filter('#NS').text();
if (NS == '1') {
$('#NS').prop('checked', true);
} else {
$('#NS').prop('checked', false);
}
var RDO = $($(html).filter('#' + self.id).html()).filter('#A12').text();
if (RDO == '1') {
$('#RDO').prop('checked', true);
} else {
$('#RDO').prop('checked', false);
}
var OrdHours = $($(html).filter('#' + self.id).html()).filter('#A5').text();
$("#ordhrs").val(OrdHours);
var x150 = $($(html).filter('#' + self.id).html()).filter('#A11').text();
$("#OTx150").val(x150);
var departmentID = $($(html).filter('#' + self.id).html()).filter('#A6').text();
$("select#ChangeDeparment").val(departmentID);
total = $($(html).filter('#' + self.id).html()).filter('#A8').html();
totalhrs = $($(html).filter('#' + self.id).html()).filter('#A7').html();
$("#total").html(totalhrs + "<br />" + total);
adjustmentID = $($(html).filter('#' + self.id).html()).filter('#B1').text();
no_adjustment = false;
$(self).dialog("close");
}
}
newArray.push(window["button" + self.id]);
}
});