sharepoint javascript on click shape - javascript

I need to add an onclick event to shapes from Visio in SharePoint, with JavaScript, like the vwaControl handler shapeselectionchanged but on click, is there any way I could do that?
I'm sorry about my English is not my native language.
I hope you can understand me.

I just did something similar.
You can use the shapeSelectionChangedHandler to handle clicks to. As far as I know there is no onClick functionality, but shapeSelectionChangedHandler works fine for me.
See:
Programming with Visio in SharePoint, create new Outlook meeting in ?Javascript?
See: http://msdn.microsoft.com/en-us/library/gg243427.aspx for guide to set it up with Content WebPart and so on.
Code I use, just add what you want in shapeSelectionChangedHandler = function(source, args) {}
<script language="javascript">
var app = Sys.Application;
app.add_load(onApplicationLoad);
// hold an instance of the Visio VWA control
var vwaControl;
var shapeSelectionChangedHandler = null;
function onApplicationLoad()
{
vwaControl= new Vwa.VwaControl("WebPartWPQ4");
vwaControl.addHandler("diagramcomplete", onDiagramComplete);
vwaControl.addHandler("shapeselectionchanged", shapeSelectionChangedHandler);
}
function onDiagramComplete()
{
var vwaPage = vwaControl.getActivePage();
vwaPage.setZoom(35); // force the initial zoom level
}
shapeSelectionChangedHandler = function(source, args)
{
// get the selected shape from the shapes on the page
var vwaPage = vwaControl.getActivePage();
var vwaShapes = vwaPage.getShapes();
var shape = vwaShapes.getItemById(args);
// get the data to display for the selected shape
var data = shape.getShapeData();
var strRoomName = "";
var strFloorNumber = "";
var strCapacity = "";
var strStatus = "";
for (var j = 0; j < data.length; j++)
{
if (data[j].label == "RoomName")
{
strRoomName = data[j].value;
continue;
}
if (data[j].label == "FloorNumber")
{
strFloorNumber = data[j].value;
continue;
}
if (data[j].label == "Capacity")
{
strCapacity = data[j].value;
continue;
}
if (data[j].label == "RoomStatus")
{
strStatus = data[j].value;
continue;
}
}
// get the selected state input and set its value
var inputRoomName = document.getElementById('strRoomName');
inputRoomName.value = strRoomName;
var inputFloorNumber = document.getElementById('strFloorNumber');
inputFloorNumber.value = strFloorNumber;
var inputCapacity = document.getElementById('strCapacity');
inputCapacity.value = strCapacity;
var inputStatus = document.getElementById('strStatus');
inputStatus.value = strStatus;
}

Related

Updating value in for loop / Reseting a for loop?

I'm working on my first school project so I don't have much experience in doing such web applications, that's why I decided to ask here.
How can I update the value in the for loop syntax or reset it entirely, so it iterates again, like I just reloaded it? I have another function that I decided not to show, simply because it would be useless to. What it does in the end is increments the taskCount.length by one. This part technically works but problem is, the function I'm going to show you now, once iterated, will always keep the default taskCount.length value, once the page is loaded, it never changes there. Is there any way I can update it?
Here's an example: The function above makes taskCount.length = '5' but when the page started it was taskCount.length = 4, and when I do alert(taskCount.length) from the console, I get 5. But the for loop doesn't want to change.
for (var i = 0; i < taskCount.length; i++) {
document.getElementsByClassName('task')[i].addEventListener('click', ((j) => {
return function() {
var shadow = document.createElement('div');
// Styling
var changingWindow = document.createElement('div');
// Styling
var changingTitle = document.createElement('p');
// Styling
var changingText = document.createElement('p');
// Styling
var changingTitleNode = document.createTextNode('Промяна');
var changingTextNode = document.createTextNode('Моля, изберете действие.');
var deleteTask = document.createElement('button');
var goUp = document.createElement('button');
var goDown = document.createElement('button');
var unchange = document.createElement('button');
// Styling
var deleteElementNode = document.createTextNode('Премахни задачата');
var goUpNode = document.createTextNode('Премести нагоре');
var goDownNode = document.createTextNode('Премести надолу');
var unchangeNode = document.createTextNode('Отказ');
var justBreak = document.createElement('br');
var justBreakAgain = document.createElement('br');
var justBreakOneMoreTime = document.createElement('br');
body.appendChild(shadow);
shadow.appendChild(changingWindow);
changingWindow.appendChild(changingTitle);
changingTitle.appendChild(changingTitleNode);
changingWindow.appendChild(changingText);
changingText.appendChild(changingTextNode);
changingWindow.appendChild(deleteTask);
deleteTask.appendChild(deleteElementNode);
deleteTask.onclick = function() {
document.getElementsByClassName('task')[j].parentNode.removeChild(document.getElementsByClassName('task')[j]);
shadow.parentNode.removeChild(shadow);
localStorage.setItem("listContent", document.getElementById('list').innerHTML);
}
changingWindow.appendChild(justBreak);
changingWindow.appendChild(goUp);
goUp.appendChild(goUpNode);
goUp.onclick = function() {
if (j !== 0) {
var saveThisTaskValue = document.getElementsByClassName('task')[j].innerHTML;
var savePreviousTaskValue = document.getElementsByClassName('task')[j - 1].innerHTML;
document.getElementsByClassName('task')[j].innerHTML = savePreviousTaskValue;
document.getElementsByClassName('task')[j - 1].innerHTML = saveThisTaskValue;
}
shadow.parentNode.removeChild(shadow);
localStorage.setItem("listContent", document.getElementById('list').innerHTML);
}
changingWindow.appendChild(justBreakAgain);
changingWindow.appendChild(goDown);
goDown.appendChild(goDownNode);
goDown.onclick = function() {
if (j !== document.getElementsByClassName('task').length - 1) {
var saveThisTaskValue = document.getElementsByClassName('task')[j].innerHTML;
var saveNextTaskValue = document.getElementsByClassName('task')[j + 1].innerHTML;
document.getElementsByClassName('task')[j].innerHTML = saveNextTaskValue;
document.getElementsByClassName('task')[j + 1].innerHTML = saveThisTaskValue;
}
shadow.parentNode.removeChild(shadow);
localStorage.setItem("listContent", document.getElementById('list').innerHTML);
}
changingWindow.appendChild(justBreakOneMoreTime);
changingWindow.appendChild(unchange);
unchange.appendChild(unchangeNode);
unchange.onclick = function() {
shadow.parentNode.removeChild(shadow);
}
}
})(i))
}
As a matter of the page reloading, you can always save the value as a cookie and reuse it again and again. You can update it whenever you want.
I don't fully understand you question, but maybe some recursion is what you need. Something along the lines of:
loop(5);
function loop(xTimes) {
for (var i = 0; i < xTimes; i++) {
if (newXTimes !== xTimes) {
loop(newXtimes);
break;
}
}
}
Maybe set newxTimes as a global variable that can be accessed inside loop.
In case someone "from the future" reads this question and it doesn't have any answers, I came up with the solution to reload the page everytime you change the value. Still, I'd like to do it without reloading.

TypeError: Cannot read property "length" from undefined variables

I have worked with code that pulls table information off a site and then places into Google Sheets. While this had worked great for months, it has come to my attention that is has randomly stopped working.
I am getting the message "TypeError: Cannot read property "length" from undefined." From code:
for (var c=0; c<current_adds_array.length; c++) {
I have done extensive searching but cannot come to conclusion as to what is wrong.
Full code seen here:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Get Data')
.addItem('Add new dispatch items','addNewThings')
.addToUi();
}
function addNewThings() {
// get page
var html = UrlFetchApp.fetch("#").getContentText();
// bypass google's new XmlService because html isn't well-formed
var doc = Xml.parse(html, true);
var bodyHtml = doc.html.body.toXmlString();
// but still use XmlService so we can use getDescendants() and getChild(), etc.
// see: https://developers.google.com/apps-script/reference/xml-service/
doc = XmlService.parse(bodyHtml);
var html = doc.getRootElement();
// a way to dig around
// Logger.log(doc.getRootElement().getChild('form').getChildren('table'));
// find and dig into table using getElementById and getElementsByTagName (by class fails)
var tablecontents = getElementById(html, 'formId:tableExUpdateId');
// we could dig deeper by tag name (next two lines)
// var tbodycontents = getElementsByTagName(tablecontents, 'tbody');
// var trcontents = getElementsByTagName(tbodycontents, 'tr');
// or just get it directly, since we know it's immediate children
var trcontents = tablecontents.getChild('tbody').getChildren('tr');
// create a nice little array to pass
var current_adds_array = Array();
// now let's iterate through them
for (var i=0; i<trcontents.length; i++) {
//Logger.log(trcontents[i].getDescendants());
// and grab all the spans
var trcontentsspan = getElementsByTagName(trcontents[i], 'span');
// if there's as many as expected, let's get values
if (trcontentsspan.length > 5) {
var call_num = trcontentsspan[0].getValue();
var call_time = trcontentsspan[1].getValue();
var rptd_location = trcontentsspan[2].getValue();
var rptd_district = trcontentsspan[3].getValue();
var call_nature = trcontentsspan[4].getValue();
var call_status = trcontentsspan[5].getValue();
//saveRow(call_num, call_time, rptd_location, rptd_district, call_nature, call_status);
current_adds_array.push(Array(call_num, call_time, rptd_location, rptd_district, call_nature, call_status));
}
}
saveRow(current_adds_array);
}
//doGet();
function saveRow(current_adds_array) {
// load in sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// find the current last row to make data range
var current_last_row = sheet.getLastRow();
var current_last_row_begin = current_last_row - 50;
if (current_last_row_begin < 1) current_last_row_begin = 1;
if (current_last_row < 1) current_last_row = 1;
//Logger.log("A"+current_last_row_begin+":F"+current_last_row);
var last_x_rows = sheet.getRange("A"+current_last_row_begin+":F"+current_last_row).getValues();
var call_num, call_time, rptd_location, rptd_district, call_nature, call_status;
// iterate through the current adds array
for (var c=0; c<current_adds_array.length; c++) {
call_num = current_adds_array[c][0];
call_time = current_adds_array[c][1];
rptd_location = current_adds_array[c][2];
rptd_district = current_adds_array[c][3];
call_nature = current_adds_array[c][4];
call_status = current_adds_array[c][5];
// find out if the ID is already there
var is_in_spreadsheet = false;
for (var i=0; i<last_x_rows.length; i++) {
//Logger.log(call_num+" == "+last_15_rows[i][0]);
if (call_num == last_x_rows[i][0] && call_time != last_x_rows[i][1]) is_in_spreadsheet = true;
}
Logger.log(is_in_spreadsheet);
//Logger.log(last_15_rows.length);
if (!is_in_spreadsheet) {
Logger.log("Adding "+call_num);
sheet.appendRow([call_num,call_time,rptd_location,rptd_district,call_nature,call_status]);
}
}
}
function getElementById(element, idToFind) {
var descendants = element.getDescendants();
for(i in descendants) {
var elt = descendants[i].asElement();
if( elt !=null) {
var id = elt.getAttribute('id');
if( id !=null && id.getValue()== idToFind) return elt;
}
}
}
function clearRange() {
//replace 'Sheet1' with your actual sheet name
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
sheet.getRange('A2:F').clearContent();}
function getElementsByTagName(element, tagName) {
var data = [];
var descendants = element.getDescendants();
for(i in descendants) {
var elt = descendants[i].asElement();
if( elt !=null && elt.getName()== tagName) data.push(elt);
}
return data;
}
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("C:C");
range.setValues(range.getValues().map(function(row) {
return [row[0].replace(/MKE$/, " Milwaukee, Wisconsin")];
}));
Please be careful when instantiating a new array. You are currently using var current_adds_array = Array(). You're not only missing the new keyword, but also, this constructor is intended to instantiate an Array with an Array-like object.
Try changing this to var current_adds_array = []

Is there possible to add a moreLink to display all events in a popup regardless the space available in the dayCell?

I am trying to add a moreLink in full calendar on each day i have events and in the more link i want to force displaying all the events on that day!
this is the solutin i choose because the title of the events are very long and do not fit in a tablet or phone screen!
so far i am unsuccesfull on the days i have one single event because the function computeRowLevelLimit returns false!
i am open to any crazy idea that helps me but keep in mind that i am a java dev with minimal kowledge of js and add some extra info if possible
since i was under presure i took the matter in my own hands so here is the resolve
here i added the last else in order to be able to execute 2 methods when levelLimit is false
limitRows: function (levelLimit) {
var rowStructs = this.eventRenderer.rowStructs || [];
var row; // row #
var rowLevelLimit;
for (row = 0; row < rowStructs.length; row++) {
this.unlimitRow(row);
if (!levelLimit) {
rowLevelLimit = false;
}
else if (typeof levelLimit === 'number') {
rowLevelLimit = levelLimit;
}
else {
rowLevelLimit = this.computeRowLevelLimit(row);
}
if (rowLevelLimit !== false) {
this.limitRow(row, rowLevelLimit);
} else {
this.unlimitRow2(row);
this.addMoreLink(row);
}
}
},
The added metod are:
- one for clearing the existing links
- second for adding new links - remember this is for days with only one event
the methods are the following:
unlimitRow2: function (row) {
var rowStruct = this.eventRenderer.rowStructs[row];
var cellMatrix;
var oneDayCell;
cellMatrix = rowStruct.cellMatrix;
var _this = this;
for (i = 0; i < cellMatrix.length; i++) {
// console.log("celmatrix ", cellMatrix[i]);
oneDayCell = cellMatrix[i];
console.log("outati", oneDayCell)
if (oneDayCell.moreEls) {
oneDayCell.moreEls.remove();
oneDayCell.moreEls = null;
}
if (oneDayCell.limitedEls) {
oneDayCell.limitedEls.removeClass('fc-limited');
oneDayCell.limitedEls = null;
}
}
},
and,
addMoreLink: function (row) {
// console.log("inside addMoreMethod", row);
var rowStruct = this.eventRenderer.rowStructs[row];
var cellMatrix;
var oneDayCell;
var coloana;
var nrCol;
var td, moreWrap, moreLink;
var moreNodes = [];
var segsBelow;
// console.log ("structura randului", rowStruct);
cellMatrix = rowStruct.cellMatrix;
var _this = this;
for (i = 0; i < cellMatrix.length; i++) {
// console.log("celmatrix ", cellMatrix[i]);
oneDayCell = cellMatrix[i];
for (j = 0; j < oneDayCell.length; j++) {
coloana = oneDayCell[j];
nrCol = j;
segsBelow = _this.getCellSegs(row, nrCol);
console.log($(coloana));
moreLink = _this.renderMoreLink(row, nrCol, segsBelow);
moreWrap = $('<div/>').append(moreLink);
coloana.append(moreWrap);
moreNodes.push(moreWrap[0]);
// rowStruct.limitedEls = $(limitedNodes);
}
rowStruct.moreEls = $(moreNodes); // for easy undoing later
}
},
and for the rest i manipulated a litle bit limitRow: function (row, levelLimit)
also i had to hide the text and i choose a nasty method, not proud of it but ...
in getMoreLinkText(num) i added a last else if
else if (num === 0 ){
return '';
}

Change Firefox Bookmarks To TitleCase (Capitalize Each Word)

This My First Question Hear In Stack Overflow, And I Wish To Get The Help I Expect..
I Was Looking For A Way To Change All The Firefox Bookmarks Titles
To 'TitleCase' .
I've already found a perfect technique to change it to UPPERCase using a fierfox Dev. tool
called "scratchpad" in the browser environment .
here's the steps for it:-
open about:config
set devtools.chrome.enabled to true
tools > web developer > scratchpad
environment > browser
edit > paste (i.e. copy and paste code below)
execute > run
Code.
function getChildIds(aRootNode, aChildIds) {
for (var i = 0; i < aRootNode.childCount; i++) {
var node = aRootNode.getChild(i);
aChildIds.push(node.itemId);
if (node.type == node.RESULT_TYPE_FOLDER) {
node.QueryInterface(Ci.nsINavHistoryContainerResultNode);
var oldContainerOpen = node.containerOpen;
node.containerOpen = true;
getChildIds(node, aChildIds);
node.containerOpen = oldContainerOpen;
}
}
}
var bs = Cc["#mozilla.org/browser/nav-bookmarks-service;1"].
getService(Ci.nsINavBookmarksService);
var hs = Cc["#mozilla.org/browser/nav-history-service;1"].
getService(Ci.nsINavHistoryService);
var query = hs.getNewQuery();
var options = hs.getNewQueryOptions();
options.queryType = options.QUERY_TYPE_BOOKMARKS;
var folders = new Array();
folders.push(bs.bookmarksMenuFolder); // Bookmarks Menu
folders.push(bs.toolbarFolder); // Bookmarks Toolbar
folders.push(bs.unfiledBookmarksFolder); // Unsorted Bookmarks
var childIds = new Array();
for (var i = 0; i < folders.length; i++) {
query.setFolders(folders.slice(i, i + 1), 1);
var result = hs.executeQuery(query, options);
var rootNode = result.root;
rootNode.containerOpen = true;
getChildIds(rootNode, childIds); // recursive function
rootNode.containerOpen = false;
}
bs.runInBatchMode({
runBatched: function () {
for (var i = 0; i < childIds.length; i++) {
var type = bs.getItemType(childIds[i]);
if (type == bs.TYPE_BOOKMARK || type == bs.TYPE_FOLDER) {
var title = bs.getItemTitle(childIds[i]);
if (title) {
bs.setItemTitle(childIds[i], title.toUpperCase());
}
}
}
}
}, null);
So, My Question Is, How To Modify That Code In Order To Change The Bookkmarks' Titles
To TitleCase (Capitalize Each Word) ?
Thanks In Advance...
See this website:
http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase(v=vs.110).aspx
You can use the method ToTitleCase from the TextInfo class to change a string to title case. (Make sure that the title variable is a string.) Then, instead of using title.toUpperCase use title.ToTitleCase.
I hope this helps,
Santiago

Google Apps Script: How to get this code run after UI is closed?

This may seem a very newbie question, but I'm stuck with it. I've got this code to show a check list in a UI and insert the paragraphs of one or more documents into another target document:
var fact_list = [ ["Kennedy Inauguration", "politics", "tZwnNdFNkNklYc3pVUzZINUV4eUtWVWFSVEf"], ["Pericles’ Funeral Oration", "politics", "sdgrewaNkNklYc3pVUzZINUV4eUtW345ufaZ"], ["The Pleasure of Books", "culture", "1234rFszdgrfYc3pVUzZINUV4eU43usacd"], ["I Am The First Accused (Nelson Mandela)", "law", "34rsgadOsidjSZIswjadi95uydnfklsdks"] ];
function showList() {
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication();
var panel = app.createVerticalPanel().setId('panel');
// Store the number of items in the array (fact_list)
panel.add(app.createHidden('checkbox_total', fact_list.length));
// add 1 checkbox + 1 hidden field per item
for(var i = 0; i < fact_list.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(fact_list[i][0]);
var hidden = app.createHidden('checkbox_value_'+i, fact_list[i]);
panel.add(checkbox).add(hidden);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
app.add(panel);
mydoc.show(app);
}
function submit(e){
var numberOfItems = e.parameter.checkbox_total;
var itemsSelected = [];
// for each item, if it is checked / selected, add it to itemsSelected
for(var i = 0; i < numberOfItems; i++){
if(e.parameter['checkbox_isChecked_'+i] == 'true'){
itemsSelected.push(e.parameter['checkbox_value_'+i]);
}
}
var app = UiApp.getActiveApplication();
ScriptProperties.setProperties({'theses': itemsSelected}, true);
app.close();
return app;
}
function importTheses(targetDocId, thesesId, thesesType) { // adapted from Serge insas
var targetDoc = DocumentApp.openById(targetDocId);
var targetDocParagraphs = targetDoc.getParagraphs();
var targetDocElements = targetDocParagraphs.getNumChildren();
var thesesDoc = DocumentApp.openById(thesesId);
var thesesParagraphs = thesesDoc.getParagraphs();
var thesesElements = thesesDoc.getNumChildren();
var eltargetDoc=[];
var elTheses=[];
for( var j = 0; j < targetDocElements; ++j ) {
var targetDocElement = targetDoc.getChild(j);
// Logger.log(j + " : " + type);// to see targetDoc's content
eltargetDoc[j]=targetDocElement.getText();
if(el[j]== thesesType){
for( var k = 0; k < thesesParagraphs-1; ++k ) {
var thesesElement = thesesDoc.getChild(k);
elTheses[k] = thesesDoc.getText();
targetDoc.insertParagraph(j, elTheses[k]);
}
}
}
}
But when I call these functions inside my main function, I got a red message (in my language): service not available: Docs and, after the UI from showList() is closed, nothing more happens with my code (but I wanted the main functions continues to run). I call these functions this way:
if (theses == 1){
showList();
var thesesArrays = ScriptProperties.getProperty('theses');
for (var i = 0; i < thesesArrays.lenght(); i++){
var thesesId = ScriptProperties.getProperty('theses')[i][2];
var thesesType = ScriptProperties.getProperty('theses')[i][1];
importTheses(target, thesesId, thesesType);
}
}
showURL(docName, link); // Shows document name and link in UI
So, how can I fix that? How can I get the code run until the line showURL(docName, link);?
showList();
This function creates only Ui.
You are setting the script properties only in the Server Handler which executes on the click of submit button. Since then:
ScriptProperties.getProperty('theses');
will hold nothing. So you need to call these lines:
var thesesArrays = ScriptProperties.getProperty('theses');
for (var i = 0; i < thesesArrays.lenght(); i++){
var thesesId = ScriptProperties.getProperty('theses')[i][2];
var thesesType = ScriptProperties.getProperty('theses')[i][1];
importTheses(target, thesesId, thesesType);
}
Inside server handler or put them inside a method and call the method from the server Handler.

Categories

Resources