Posts

Showing posts with the label javascript

SharePoint - Errore javascript nel file WebResource.axd

Image
Non so dire perché, né spiegarlo o trovare traccia del motivo per cui si presenta, ma ogni tanto, non su tutti i browser, non a tutti gli utenti, e neppure allo stesso utente nella stessa sessione di navigazione, però in pagine particolarmente personalizzate lato client (tramite jquery e javascript di varia forma), viene fuori un errore javascript 'Event' is undefined normalmente in una delle righe del file WebResource.axd. In alcune circostanze, non è neppure bloccante, in altre invece blocca l'esecuzione di altri javascript (soprattutto per browser datati, ad es IE7-8) Proviamo a risolvere o aggirare il problema. Eseguendo il debug di IE l'errore non si presenta. Il che dà conferma alla teoria che l'osservazione modifica lo stato (fisica in background), ma non ci aiuta. Entrando però in debug al momento dell'errore, ecco che abbiamo un'eccezione in questa funzione, dentro il WebResource.axd (riga 184 circa): function Menu_HideItems(items) {...

SharePoint - Check People Picker con jQuery

Se si vuol controllare il valore inserito in un People Picker utilizzando jQuery, facciamo così! Controllando l'HTML source della pagina, vediamo che al People Picker corrispondono molto elementi, ma quando l'utente scrive il nome per inserire l'utente, non scrive in un input o in una textarea, ma... in un DIV con l'attributo contentEditable = true. Possiamo quindi controllare il dato in un New/Edit form prima di salvare l'item tramite la funzione js PreSaveAction(). Prima di tutto, creiamo un custom form (new o edit) e cerchiamo la riga corrispondente alla colonna People da controllare. Nell'HTML, individuiamo la TD che contiene il controllo SharePoint e aggiungiamo all'attributo "class" un nome che ci aiuterà ad identificare il campo desiderato (ad es "check-this-pp"). Se abbiamo da controllare più People Picker, usiamo classi diverse. Ora, aggiungiamo i riferimenti a jQuery e il codice seguente, in fondo alla pagina: functio...

SharePoint - Check File Name in Upload form in Document Library con Javascript

Image
Se si desidera controllare il nome del file di un nuovo documento in un Upload form, possiamo farlo con del buon Javascript ! Ho creato una funzione che controlla il nome del file e poi disattiva il bottone OK se la condizione non è verificata Ho eseguito un override della funzione CheckAssetLibMediaExtension sull'evento "onchange" del controllo input file nel file Upload.aspx. Se vediamo il codice HTML del file Upload.aspx (da browser), troviamo: <input name="ctl00$PlaceHolderMain$UploadDocumentSection$ctl05$InputFile" type="file" id="ctl00_PlaceHolderMain_UploadDocumentSection_ctl05_InputFile" class="ms-fileinput ms-fullWidth" size="35" onfocus="ResetSpFormOnSubmitCalled();"  onchange="CheckAssetLibMediaExtension()"  title="Scegliere un file" /> Cercando la funzione, troviamo: function CheckAssetLibMediaExtension() { } Così, possiamo farne l'override! Creiamo...

SharePoint - Add button Apply to List Item Edit Form for Saving Item without closing form

This post describes how to create an Apply button in list item edit form, to save data and reload form, without redirect to list (or Source). Create a custom edit form with SharePoint Designer. Open form in edit mode. Create new parameter of type QueryString for Source, named Source: when page refresh after saving data, url maintains Source (i.e. for redirect to list when you click on Save or Cancel). Then, search for this code <xsl:param name="dvt_apos">&apos;</xsl:param> <xsl:variable name="dvt_1_automode">0</xsl:variable> And add code below: <xsl:param name="ListItemId">0</xsl:param> <xsl:param name="Source"></xsl:param> Search for button save/cancel in xslt, find this code: <SharePoint:SaveButton runat="server" ControlMode="Edit" id="savebutton2"/> Add code below (the button): <input type="button" value="Applica...

SharePoint 2010 - Open Quick Launch link in a new window

Image
The need is to open a link from the Quick Launch in a new window. When Publishing Features are not activated, we can only edit URL, name of the link and its position. But, we can use the javascript functions! Then I tried this:   Saving and clicking on the new link, the URL opens successfully in a new window BUT current page becomes white with the word [Object] ... So, I tried this trick .. and it works: The URL will open in a new window and the current page is reloaded onto itself.

SharePoint 2010 - Aprire link in una nuova finestra da Quick Launch

Image
L'esigenza è quella di aprire un link da Avvio Veloce (Quick Launch) in una nuova finestra. Quando non sono attive le Publishing Features, il link non è modificabile se non nell'URL, nel nome del link e nella sua posizione. Possiamo utilizzare le funzioni javascript. Allora ho provato con questo:  Ma salvando e cliccando sul nuovo link, l'URL si apre correttamente in una nuova finestra MA la pagina corrente diventa bianca con la scritta [Object]... Allora, ho provato questo trucco e .. funziona: L'URL si apre in una nuova finestra e la pagina corrente si ricarica su se stessa.

SharePoint 2010 - Nascondere bottoni del Ribbon con jquery (javascript)

Image
Il Ribbon, questo ormai nostro compagno di viaggio nel mondo Microsoft. Se lo conosci, scopri ogni volta quanto sia effettivamente utile a contestualizzare le tue azioni su documenti, item, ... Una novità, introdotta ormai da MS, anche in altri ambienti, dopo Office, SharePoint, anche il nuovo CRM e persino ora Windows8... Ma ad alcuni nostri clienti ancora può non piacere. Ebbene sì. Così "perché non mi rimuovete quel tastino lì?", "perché non mi mostrate solo quello, ma solo per questa library, non per quella, ecc?"... Tramite Object Model, possiamo "tranquillamente", con almeno un tre etti di righe di XML, riuscire a nascondere, disabilitare, modificare le funzioni, i bottoni, l'aspetto, gli eventi per la maggior parte dei pulsanti. Ma ogni tanto, non è necessario intervenire così a fondo, magari non si ha sempre a disposizione una risorsa di sviluppo da utilizzare (o l'ambiente di sviluppo). Così, l'ormai mitico jquery, è qui...

SharePoint 2010 - Inserire come Title il Name del documento caricato con javascript!

Quante volte mi sono trovato in difficoltà a .. giustificare il perché SharePoint non mette come Title del Documento caricato il Name dello stesso..!? Lo fa, certo, se si tratta di un documento Office correttamente compilato (ad es. un file Word con la proprietà Title, o un PDF..) Ma non lo fa sempre, o non sempre i documenti sono correttamente compilati. Una strada è l'Event Receiver, ma occorre compilare del codice, non sempre possibile, su tutti gli ambienti dei nostri clienti. Così, la strada del javascript (o con più facilità, con jquery). Nota : questa strada è possibile SE tutti i nuovi documenti sono caricati tramite la form di upload o modificando le proprietà da browser! Per upload massivi o creazione di nuovi documenti da template, questo discorso non è valido ed è necessario intervenire con l'Event Receiver! Modifichiamo la master page, con il richiamo alle librerie jquery e con l'inseriemto del codice sottostante: function SetFieldTitleFromNameAut...

Sharepoint 2007 - Modal Dialog Sharepoint2010-Like

Image
Or .. How to show modal dialog with page content only. In Sharepoint 2007 we don't have a client script framework that shows modal dialogs with ligthbox effect, as in Sharepoint 2010. We can reproduce with a lot of jquery ui and similia. In MOSS, we can use the function javascript of core.js,  commonShowModalDialog. Open Site and in Homepage, add a Content Editor Web Part with this simple code: <a href="javascript:openInModalDialog()">CLICK HERE</a> <script type="text/javascript"> function openInModalDialog() {   var url = "/Lists/Calendar/Calendar.aspx";   commonShowModalDialog(url,"resizable: no; status:no; scroll: no; help: no; center: yes; dialogwidth:800px; dialogHeight:500px;",RetrieveItemValue); } </script> Click on link opens modal dialog, but we show the entire page in window: Now, open Calendar page in edit mode. Add Content Editor Web Part at the bottom of the page with code belo...

Sharepoint 2010 - Customizing Quick Launch with pages

Image
How to show different quick launch menu items in different pages? The quick launch in Sharepoint is an object common to all pages of the site. To show menu items according to the page you visited, I followed client side method with javascript (jquery). Here's how, using Sharepoint Designer 2010. On css stylesheet of the site, I added this instruction, which hides all the items in the Quick Launch: . s4-ql ul.root> li { display: none; } Then, make note of the position of the menu items in the quick lanuch: eg. 0 - Document Libraries 1 - Lists 2 - MyLink      0 - MySubLink1      1 - MySubLink2 3 - MyOtherLink 4 - MyLastLink The pages follows the following rules: Page1 shows 0,1,4 Page2 shows 0,2,3 Page3 shows 0,2 (and sub ​​links 1), 3.4 And now, I change the master.page, adding references to jquery and inserting the following code: //get all items in the quick launch var li_nav = $(".vertical-menu>ul>li"); //get...

Resizing Cross-Domain IFrame with Javascript

I tried to find a way to pass height of page loaded in an IFRAME to parent document in order to reset the height of the IFRAME with javascript. It's a simple coding, but .. if you use IFRAME with a page in a different domain, you cannot access to properties of page opened in IFRAME and from page to opener. The idea is to be able to pass the value of the height of the content at regular intervals, using a javascript function, and try to read it by the parent. This applies to the height value, but works for any data, of small size, to be passed client side from content of the iframe to container in a cross domain situation. Obviously, if we can access page open iframe in edit. NOTE: Both domains must be added to Trusted Sites. Let's see how. I put the following function in the page that I want to load iframe: setInterval (function () {this.frames.status = getHeight();}, 400); getHeight function () {      var height;     [we calculate body heig...

Sharepoint 2010 - Client Validation of a Custom Form with Javascript

What to do if you want to perform a client validation with Javascript, in your custom new/edit form. The submit button cames with this code in onclick event: if ( !PreSaveItem()_ ) return false;WebForm_DoPostBackWithOptions(new .. . The PreSaveItem function invokes PreSaveAction function that you can override with your own definition. If PreSaveAction returns true, then form proceeds to save data, otherwise, it stops with alert. With Sharepoint Designer 2010, open form with Edit in Advanced Mode and insert code below: <!-- call jquery --> <script type="text/javascript" src="/SiteAssets/js/jquery.min.js"></script> <!-- override PreSaveAction --> <script type="text/javascript"> function PreSaveAction() {     var field_to_validate = $("select[title='TITLE OF FIELD']").val();    if(field_to_validate == "") {      alert("Warning: complete field_to_validate!");      return ...

Get QueryString Value with JQuery

I found this solution to get value of querystring with jquery. Add jquery script to your page and insert this code in script to define the new function: (function($) {     $.QueryString = (function(a) {         if (a == "") return {};         var b = {};         for (var i = 0; i < a.length; ++i)         {             var p=a[i].split('=');             if (p.length != 2) continue;             b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));         }         return b;     })(window.location.search.substr(1).split('&')) })(jQuery); Then, call it for your querystring parameter: var q = $.QueryString["query"]; Fine!

Sharepoint 2010 - Change UI Language with javascript

If you want to use html/javascript to change UI language, you can use the script below: (Note: in the page, there is the function OnSelectionChange, so you have to change name if you want to use other feature in) function OnSelectionChange(value) {     var today = new Date();     var oneYear = new Date(today.getTime() + 365 * 24 * 60 * 60 * 1000);     var url = window.location.href;     document.cookie = "lcid=" + value + ";path=/;expires=" + oneYear.toGMTString();     window.location.href = url; } And in page, set the flags for change language: <a href="javascript:OnSelectionChange(1040)">     <img width="32" height="20" src="/SiteAssets/flag_ita.png" border="0" alt="Italiano"/> </a> <a href="javascript:OnSelectionChange(1033)">     <img width="32" height="20" src="/SiteAssets/flag_eng.png" border="0" alt=...

Sharepoint 2010 - Modify Documents Properties with ECMA Script

Finally I found the way to modify document properties with ECMA Script! It's not an hard work for Document Libraries with no mandatory check out. Here the script: function updateDocument(action, docLibId, docId, fieldName, fieldValue) {     var context = new SP.ClientContext.get_current();       var web = context.get_web();       var docLibGuid = new SP.Guid(docLibId);       var docLib = web.get_lists().getById(docLibGuid);       var doc = docLib.getItemById(docId);       doc.set_item(fieldName, fieldValue);         doc.update();       context.executeQueryAsync(Function.createDelegate(this, this.successUpdateDocument), Function.createDelegate(this, this.failed));  } function successUpdateDocument(sender, args) {       //reload page if success       location.reload(true); } But when we set check out mandatory, we ...

LyteBox sulle immagini inserite in Blogger

Image
Ovviamente non l'ho scoperto io né tantomeno me lo sono inventato. Copio e incollo un riassunto delle istruzioni per l'effetto tipo Lightbox per le immagini inserite in questo Blog! Andare su Layout > Modifica HTML e, dopo aver salvato il modello completo, cercate la riga </head>, quindi, immediatamente sopra incollateci il seguente codice (ovviamente potete scaricare i file necessari e metterli dove volete): <!-- EFFETTO LYTEBOX INIZIO --> <link href='https://sites.google.com/site/ideepercomputeredinternet/script-1/lytebox-stile-2.css' media='screen' rel='stylesheet' type='text/css'/> <script src='http://sites.google.com/site/ideepercomputeredinternet/script-menu/lytebox-script.js' type='text/javascript'/> <!-- EFFETTO LYTEBOX FINE --> Salvate il modello e la personalizzazione è completata. Per attivarla bisogna operare sul codice delle foto inserite. Si possono ottenere effetti su u...